Skip to content

Instantly share code, notes, and snippets.

@arniebradfo
Last active June 23, 2022 18:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arniebradfo/f45a7438a372c32cb3bd0046559530a6 to your computer and use it in GitHub Desktop.
Save arniebradfo/f45a7438a372c32cb3bd0046559530a6 to your computer and use it in GitHub Desktop.
WordPress shortcode that adds classes to the html body
<?php // ...in functions.php
// adds wp shortcode that adds css classes to the html body
// use in your page and post content like this:
// [bodyclass class="add these classes to the body"]
function use_bodyclass_shortcode( $classes ) {
global $post;
// check if the post has the bodyclass shortcode
if( isset($post->post_content) && has_shortcode( $post->post_content, 'bodyclass' ) ){
// match the content of the first class="content" attribute in the bodyclass shortcode
preg_match('/\[bodyclass(?:\s|\s[^\]]*\s)class=[\"\']([^\"\'\]]*)[\"\'][^\]]*\]/i', $post->post_content, $matches);
// transform the matched string into an array of classes
$addedClasses = explode(' ', $matches[1]);
// add the new array to the wp body classes array
$classes = array_merge($classes,$addedClasses);
}
return $classes;
}
add_filter( 'body_class', 'use_bodyclass_shortcode' );
// register the bodyclass function with WordPress will not return anything extra
function bodyclass_Func( $atts, $content = null ){
return do_shortcode($content);
}
add_shortcode('bodyclass','bodyclass_Func');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment