2

Simple shortcode function :

function my_shortcode_function($atts,$content=null){
  // Do something
  return $content;
}
add_shortcode('my_shortcode','my_shortcode_function');

I wonder how to add more extra body class when user use this shortcode in contents.

I can't do something like :

function my_shortcode_function($atts,$content=null){
  // Do something
  add_filter('body_class','my_body_class');
  return $content;
}
function my_body_class($classes) {
   $classes[] = 'foo';
   return $classes;
}
add_shortcode('my_shortcode','my_shortcode_function');

Any idea ?

  • 2
    The problem is that your shortcode fires after body_class() has run. You could "sniff" for your shortcode before get_header(), but have you considered another option as opposed to needing an extra body class? What is your ultimate goal? – TheDeadMedic Apr 15 '14 at 11:17
  • i think i going to use has_shortcode inside body_class filter – l2aelba Apr 15 '14 at 11:21
7

I am doing something like this in one of my plugins:

function my_body_class( $c ) {

    global $post;

    if( isset($post->post_content) && has_shortcode( $post->post_content, 'your-shortcode' ) ) {
        $c[] = 'your-class';
    }
    return $c;
}
add_filter( 'body_class', 'my_body_class' );

I'm not sure it was really necessary, but I probably can't remove it now either. TheDeadMedic is right, you should think about whether you really need to do this.

  • Thanks i think to use has_shortcode too, In my case I have to add a class on body tag when contents has some shortcode. – l2aelba Apr 15 '14 at 11:24
  • + whatever I will use cache system :P – l2aelba Apr 15 '14 at 11:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.