How to use dynamic tags in PHP with Caldera Engine (My Shortcodes) for WordPress
I recently found a plugin that has become one of my newest favorite (besides pods), that allows you to create your own shortcodes, widgets, posts, and more. This plugin is called My Shortcodes for the free version, or Caldera Engine for the paid version (which you should get and support the dev).
So when you create a widget, you can create “attributes” that are field inputs (text box, dropdown, etc) that show up when you use the widget…well what happens when you need to use that attribute inside some of your PHP code (it also has a template engine built in)…unfortunately because of how new Caldera is there isn’t much documentation online, but there’s actually a very easy way to access these attributes and use them in your PHP code.
Inside Caldera Engine you have a few different areas for writing code. You have Template, Functions, Styles, Javascript, but the main one you will be using is going to be the Template section. Functions should only be used for just that, functions, as this is called before any of the page is loaded, and because of which, you will not have access to the regular WordPress built in functions, etc. I honestly hardly ever use this section as I just code my functions into an actual functions file included in my child theme. Reason being, is if you try to use the widget twice you will get an error saying you can’t define the function twice.
Inside the Template section you can write any PHP code you want, all you have to do is include the standard PHP open and close tags. So as a quick example, if I wanted to echo out the current WordPress user who is logged in, I could use this code inside the template area:
1 2 3 4 5 6 |
<?php $user_display_name = wp_get_current_user()->display_name; ?> <div class="container"> <?php echo $user_display_name; ?> </div> |
This is just like any PHP file you may have coded with HTML embeded in it, and if you’re lucky enough yet, you could even use the new PHP 5.4 supported echo syntax which would be
1 |
<?=$user_display_name ?> |
So now what happens when you want to include that attribute in your PHP code to generate specific output? In any standard HTML you write, all you need to do is use the {{attribute}} syntax similar to Handlebars or Swig, but you can’t use that inside PHP because the way it actually works, is similar to a standard PHP echo, and because of this, your PHP code will not execute correctly.
How can you solve this? Simple…
You actually have access to an array that includes your attributes value:
1 |
$atts['your-attribute']; |
In the example above, I created the attribute “post-type” so when I add a widget, I can specify the post type that I want to use PHP to generate a count for. In the PHP code I then use
1 |
$atts['post-type']; |
To get that value, and then do what I want with it in my PHP code. Simple and easy right? Profit!
Video