First try (do not use this ... see below "edit") :
First, you need to set your shortcode something like this:
add_shortcode( 'metashortcode', 'metashortcode_addshortcode' );
Then you will create a function in which you will need to add a hook to wp_head
with something like this:
function metashortcode_addshortcode() { add_action( 'wp_head', 'metashortcode_setmeta' ); }
Then you determine what you want to do in wp_head
:
function metashortcode_setmeta() { echo '<meta name="key" content="value">'; }
Adding [metashortcode]
should add your metadata as needed. The code was provided only to help you understand how to do this. It has not been fully tested.
Change: the previous code was just a concept and cannot work due to the execution order. Here is a working example that will get the expected result:
// Function to hook to "the_posts" (just edit the two variables) function metashortcode_mycode( $posts ) { $shortcode = 'metashortcode'; $callback_function = 'metashortcode_setmeta'; return metashortcode_shortcode_to_wphead( $posts, $shortcode, $callback_function ); } // To execute when shortcode is found function metashortcode_setmeta() { echo '<meta name="key" content="value">'; } // look for shortcode in the content and apply expected behaviour (don't edit!) function metashortcode_shortcode_to_wphead( $posts, $shortcode, $callback_function ) { if ( empty( $posts ) ) return $posts; $found = false; foreach ( $posts as $post ) { if ( stripos( $post->post_content, '[' . $shortcode ) !== false ) { add_shortcode( $shortcode, '__return_empty_string' ); $found = true; break; } } if ( $found ) add_action( 'wp_head', $callback_function ); return $posts; } // Instead of creating a shortcode, hook to the_posts add_action( 'the_posts', 'metashortcode_mycode' );
Enjoy it!
source share