Reputation: 1078
I've previously used the add_filter()
function to add a class to the body like so:
add_filter( 'body_class', 'add_custom_class' );
function add_custom_class( $classes ) {
if ( is_single() ) {
$classes[] = 'post';
}
return $classes;
}
I'd like to be able to use something along these lines to add a class to a div:
add_filter( 'div_class', 'add_custom_class' );
function add_custom_class( $classes ) {
if ( is_single() ) {
$classes[] = 'post';
}
return $classes;
}
or better still:
add_filter( 'div_class', 'add_custom_class' );
function add_custom_class( $classes ) {
if ( is_single() ) {
$classes[] = 'post';
}
else if ( is_singular( 'custom-post-type' ) ) {
$classes[] = 'custom-post-type-class';
}
return $classes;
}
And then pull in the class in my theme like so:
<div class="wrapper <?php echo div_class(); ?>">
Is this possible? Thanks in advance!
Upvotes: 1
Views: 1479
Reputation: 2432
Yes, this is entirely possible.
function so50582899_div_class($classes) {
global $post;
if(is_single()) {
$classes[] = 'single-post';
} elseif(is_page()) {
$classes[] = 'page'
}
return $classes;
}
add_filter('post_class', 'so50582899_div_class');
Then you can call it like <div class="<?php post_class(); ?>">
EDIT: To remove all existing classes add $classes = array();
to the top of the function. This will reset the classes that are returned and only return the ones you set within the function.
So it would end up like:
function so50582899_div_class($classes) {
global $post;
$classes = array();
if(is_single()) {
$classes[] = 'single-post';
} elseif(is_page()) {
$classes[] = 'page'
}
return $classes;
}
add_filter('post_class', 'so50582899_div_class');
Reference: https://codex.wordpress.org/Function_Reference/post_class#Add_Classes_By_Filters
Upvotes: 1