Documentation, Reference Materials, and Tutorials for WPCode
WPCode version 2.0.12 added support for using shortcode attributes in your snippets. What this means is that you can now pass data to your snippet when using it as a shortcode.
How are shortcode attributes useful? They make it really easy to reuse a snippet in multiple places when you only need to change a small part of the snippet, making maintenance of snippets a lot easier and less error-prone.
For example, if you own a blog where you write book reviews, you can have a snippet set up for a nice-looking author box that you want to use as a shortcode, with shortcode attributes you can pass the author name and short description to your snippet by simply adding those values as attributes for your shortcode:
[author-box name="Jules Verne" bio="French novelist, poet, and playwright"].
Before you can use shortcode attributes in your snippet you will need to register them. We added this extra step so that you have more control over which attributes are available and also to prevent the shortcode from being abused by users on your site. An attribute added to the shortcode that is not registered in the snippet settings will have no effect on the snippet.
Adding attributes is really easy, all you have to do is make sure you are in Shortcode mode in the Insertion settings box and look for Shortcode Attributes, you will find an input where you can add your shortcode attribute and clicking on the “+ Add Attribute” button will add the attribute to your snippet.
Once you save your snippet you will also notice that the shortcode that you can copy is automatically pre-filled with the defined attributes so that it’s easier for you to get started.
In the screenshot above you will notice we have a setup like the one in the previous example with 2 attributes.
Adding attributes is not going to make a difference if you can’t use them in the snippet code. When you are writing your snippet there are 2 ways in which you can access your shortcode attributes, depending on the code type.
If you are writing a PHP or Universal snippet you can access the attributes as PHP variables based on the name of the attribute you added to your snippet. For example, if your attribute is name “name” you can access that attribute in PHP as
Going further with the example above, here’s an example of what the code for a Universal snippet would look like with the 2 attributes defined above: name & bio.
This is really easy to achieve using the Smart Tags selector available in all the WPCode premium versions. As you define shortcode attributes for your snippet they will automatically show up in the Smart Tags selector:
This approach is easier and safer and we recommend it whenever possible instead of using PHP variables which can throw errors if the syntax is not correct.
Still stuck? How can we help?
Last Updated on