If meta_value = ‘yes’, then add class?

meta_key=_jsFeaturedPost meta_value=yes

I have posts where some have meta keys/values and some don’t. I would like to target the ones with the meta keys that have a value of ‘yes’ and add a CSS class to those posts so I can style them differently.

Read More

Ideally, something like: if meta_value for meta_key (jsFeaturedPost) is yes, then add class.

How would I do this?

Related posts

Leave a Reply

1 comment

  1. The post_class filter is your friend. Just combine it with get_post_meta().

    function wpse80098_filter_post_class( $classes ) {
        global $post;
        if ( 'yes' == get_post_meta( $post->ID, '_jsFeaturedPost', true ) ) {
            $classes[] = 'my-custom-css-class';
        }
        return $classes;
    }
    add_filter( 'post_class', 'wpse80098_filter_post_class' );
    

    Just replace my-custom-css-class with whatever class you want to apply to the post container in question.

    As noted in the comments, this implementation relies on the post_class() template tag being called properly in the post container, e.g.:

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

    Edit

    Re: this question in the comments:

    Is there a way I can dynamically prepend an a tag to the posts with the featured class?

    The easiest method is probably to filter the_content:

    function wpse80098_filter_the_content( $content ) {
        global $post;
        if ( 'yes' == get_post_meta( $post->ID, '_jsFeaturedPost', true ) ) {
            return '<a href="http://example.com">' . $content . '</a>';
        }
        return $classes;
    }
    add_filter( 'the_content', 'wpse80098_filter_the_content', 99 );
    

    Add a very high priority number, so that this filter gets applied last.