Once you understand the Shortcode API and how filters work, it’s easy to implement them in WordPress.
And when you’re able to mix the two, you can do much more than usual than when they are operating independently of one another.
Specifically, you can filter data that are in the result of the shortcode, and this can be especially useful for other developers. If you’re familiar with implementing custom filters, then doing this within the context of a short code isn’t much different.
But if you’ve never used either the shortcode API or the functionality before, it’s still easy to do.
Custom Filters with Shortcodes
For this post, we’ll use a relatively contrived example. That is, the shortcode will result in something static. The reason being is that it makes it easy to demonstrate in a post and implement in your code.
To implement a shortcode, you need two things:
- a custom name for the shortcode,
- a function that’s used to drop information into wherever the shortcode is used.
Note in the code above; I’ve prefixed the function with.
__NAMESPACE__ This is because the function resides within a custom namespace (which you can see at the top of the file).
Without this prefix, the function won’t be called. If you opt not to use namespaces, then you can forgo both the prefix and the leading slashes of your function name.
Note that we’ll revisit this function as soon as we have the filter in place.
Adding a custom filter is similar to adding a shortcode. You need:
- a custom filter name,
- a function that is used to filter the incoming information (and filters should generally accept at least one parameter which is, of course, the data to filter):
To keep consistent with the example above let’s say that we just want to replace a few words in the shortcode:
This will replace the content of:
This is the result of an example shortcode.
This is the result of a filtered shortcode.
But we still have to tie the two of them together.
Revisiting The Shortcode
To associate the two functions together, we need to make sure the function for the shortcode applies the filter to the value that it returns.
Luckily, implementing it is simple especially since we have everything that we need:
In a most concrete example, I always recommend checking to make sure the result of the parameter isn’t empty, that it contains the string for which I’m looking, or something similar to that.
That is, I often like to open with a guard clause. If the test fails, then I just return the incoming value; otherwise, I’ll filter the data and return whatever the result of that operation is.