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.

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

How would I do this?


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(); ?>>


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.

| improve this answer | |
  • The classes still aren't showing up for the featured posts. These posts are coming from a custom post type if that makes any difference. Here is a pastebin of how I have the template set up: pastebin.com/MHKrDQUZ – Desi Jan 10 '13 at 23:13
  • You should add the post_class template tag to the post container, in your case <li id="movie-<?php the_ID(); ?>" <?php post_class(); ?>> – diggy Jan 11 '13 at 0:34
  • Ah, thank you! I thought the function would add it automatically. – Desi Jan 11 '13 at 0:54
  • Is there a way I can dynamically prepend an a tag to the posts with the featured class? I tried something like this: $("#all-movies li.featured").prepend('<a href="<?php bloginfo("url"); ?>/hello"></a>'); but realized I couldn't because the featured class is being added dynamically. – Desi Jan 11 '13 at 7:05
  • @John that's a separate question, and should be asked separately; but I'll add something to my answer. – Chip Bennett Jan 11 '13 at 12:38

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.