Use WordPress shortcode to add <meta> tags Use WordPress shortcode to add <meta> tags wordpress wordpress

Use WordPress shortcode to add <meta> tags


First attempt (don't use this... see the 'edit' below):

First, you need to set your shortcode with something like this:

add_shortcode( 'metashortcode', 'metashortcode_addshortcode' );

Then, you'll create the function in which you'll have to add a hook to wp_head with something like that:

function metashortcode_addshortcode() {    add_action( 'wp_head', 'metashortcode_setmeta' );}

Then, you'll define what you want to do in the wp_head :

function metashortcode_setmeta() {    echo '<meta name="key" content="value">';}

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:

// 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 foundfunction 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_postsadd_action( 'the_posts', 'metashortcode_mycode' );

Enjoy!