is it possible to add a dynamic class to a div using a filter in the functions.php? I know it's possible for the body-tag - also for a custom defined div with an id?

if ( !is_search() ) {
   $customclass = 'myclass';

You could try using one of the following methods, I don't think there is a specific way to do this other than these two options below.

Option 1

In your template file, add the post_class(); to your div like this:

<div id="your-div" <?php post_class(); ?> >

Then you can use post_class filter in your themes or plugins functions file, something like this:

// Add dynamic post class
    function royal_custom_class($classes) {
        global $post;
            $classes[] = 'your-class-name'; // Add your class however its generated here
            return $classes;
    add_filter('post_class', 'royal_custom_class');

Option 2

Your other option, if the div was defined in your actual content then you could use the_content filter and replace and update it.

Something like this:

function updated_page_content( $content )
     return '<div class="custom_class">Whatever goes inside</div>'. $content;
add_filter( 'the_content', 'updated_page_content' );

References from Codex for these two methods

Post Class Filter - WordPress Codex

The Content Filter - WordPress Codex


You could also do something like (this goes into functions.php):

function add_new_class(){

    if (is_page()) {
    return "page";
} elseif (is_single()) {
    return "post";
} else {
    //add other elseifs

And then, this is how you could call this within different templates:

<header class="entry-header <?php echo $new_class = add_new_class(); ?>">

WordPress will load different value based on which template (post/page/search/archive, etc.) you are currently on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.