I'm trying to add a single class (my-class
) to an element in a WordPress post (LearnDash Theme). I fount out that it can be done using a hook via add_filter
, but no how I could figure it out.
The sample code that I found looks like this:
add_filter( 'body_class', 'custom_body_class' );
/**
* Add custom field body class(es) to the body classes.
*
* It accepts values from a per-page custom field, and only outputs when viewing a singular static Page.
*
* @param array $classes Existing body classes.
* @return array Amended body classes.
*/
function custom_body_class( array $classes ) {
$new_class = is_page() ? get_post_meta( get_the_ID(), 'body_class', true ) : null;
if ( $new_class ) {
$classes[] = $new_class;
}
return $classes;
}
In this sample code the class is added to pages only but I need to add it to "posts". I tried is_post()
but it didn't work out. I even tried it on a page, but didn't work also.
In my case I want to add a class to an element with ID learndash-page-content
.
Existing code:
<div id="learndash-page-content">...</div>
What I'm struggling to do:
<div id="learndash-page-content" >...</div>
What do I need to do to get it working?
CodePudding user response:
If that is indeed the syntax of the element, you might want to try string manipulation on the output (which you will capture like this:)
function start_modify_html() {
ob_start();
}
function end_modify_html() {
$html = ob_get_clean();
$html = str_replace( '<div id="learndash-page-content">', '<div id="learndash-page-content" >', $html );
echo $html;
}
add_action( 'wp_head', 'start_modify_html' );
add_action( 'wp_footer', 'end_modify_html' );