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 ?

1 Answer
1

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.

Leave a Reply

Your email address will not be published. Required fields are marked *