Wordpress append to HEAD from within shortcode callback

html, php, wordpress

Solution

If you want to print something to the head of the document you need use `add_action` with `wp_head` hook.

A better approach might be to not use a shortcode at all. Shortcodes are intended to add content or modify content. Instead create a function that you can attach to `wp_head` that will print your css. You may want to force the user to keep the custom field name consistent. Or better yet have your plugin add a metabox to posts that they can enter custom css into. Then you will always be certain of the name of the field.

function append_css() {

   global $post;

   if ( ! get_post_meta( $post->ID, 'mypluginname_css', true ) ) {
      return;
   }

   return '<style type="text/css">'. get_post_meta($post->ID, $key, true) .'</style>';

}

add_action( 'wp_head', 'append_css' );

The only thing i am not certain of is whether or not `$post` with the custom field data will be available outside the loop. So you may have to add some extra querying in there to pull the custom data at the time that `wp_head` is fired.

Problem

I am making a plugin, to register a shortcode, which when used like this: `[append_css mycss]` it will look for a custom field called `mycss` and add the contents to the `head` of the document. It all works great, except that the code is being added to the body, and I don't know how to get it to add to the head. I have tried adding an action `wp_head` but I don't know how to pass variables whilst doing that, and it does not seem to fire from within the shortcode callback anyway. ``` function append_css_short($params){ global $post; if(sizeof($params)){ $key = $params[0]; } else { $key = 'css'; } return '<style type="text/css">'. get_post_meta($post->ID, $key, true) .'</style>'; } add_shortcode('append_css','append_css_short'); ``` How would I get this to write to the head instead of body? Is there a better approach to the problem?

Original source