Last active
June 23, 2022 18:28
-
-
Save arniebradfo/f45a7438a372c32cb3bd0046559530a6 to your computer and use it in GitHub Desktop.
WordPress shortcode that adds classes to the html body
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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