I’m writing a simple WordPress plugin that uses shortcode. I want the page that contains the shortcode to have specific <meta>
tags. Is this possible? And if so, is there an elegant way to do it?
I know that I can add <meta>
tags with the wp_head
hook, but I want the meta tag content to match a string produced by the plugin. I could move all the code into the header, but then I’m not sure how to reference it later from the shortcode. In other words, when I declare a variable in the <head>
with a filter, it’s not available to the class methods that I’m calling with the shortcode.
Any ideas?
UPDATE:
A nice solution was proposed in which the handler function for the shortcode adds the action to the wp_head hook:
add_shortcode('fakeshortcode', 'fakeshortcode_handler');
function fakeshortcode_handler() {
function add_meta_tags() {
//echo stuff here that will go in the head
}
add_action('wp_head', 'add_meta_tags');
}
This is swell, but the problem is that wp_head happens BEFORE the shortcode gets parsed and adds the action (so nothing gets added to the head with the code above ALONE). To make it work, I borrowed the solution in this post. It’s basically a function that “looks ahead” into the post and sees if there is any shortcode coming. If it is, then IT adds the add_action('wp_head'...
.
EDIT:
I removed my follow-up question about how to pass the variable.
It’s a new question here.
First attempt (don’t use this… see the ‘edit’ below):
First, you need to set your shortcode with something like this:
Then, you’ll create the function in which you’ll have to add a hook to
wp_head
with something like that:Then, you’ll define what you want to do in the
wp_head
:Adding the shortcode
[metashortcode]
should add your meta data as needed. The code was provided only to help you understand how to make it happen. It was not fully tested.Edit : The previous code was just a concept and cannot work because of the execution order. Here is a working example that will get the expected result:
Enjoy!