I have a Post meta field in my template. I have 3 values for this meta:

  1. Yes
  2. No
  3. N/a

How can I set a custom css class according to the value ?

My code:

<span class="widget_last"><?php echo get_post_meta($post['ID'], 'Type', true); ?></span>

Thank you

1 Answer 1


Use an if or switch statement to check the value of the meta, then echo out a different class name based on the value:

$type = get_post_meta($post['ID'], 'Type', true);

switch ( $type ) {
    case 'Yes':
        $class = 'type-yes';
    case 'No':
        $class = 'type-no';
        $class = 'type-na';

<span class="widget_last <?php echo $class; ?>"><?php echo $type; ?></span>

Now you can style each type with .widget_last.type-yes, .widget_last.type-no, or .widget_last.type-na.

  • Thank you @Jacob, but I have an error: "Fatal error: Cannot use object of type WP_Post as array". The line is "$type = get_post_meta($post['ID'], 'Type', true);"
    – Garrosh
    May 11, 2018 at 13:38
  • That line was just copied from your code so it shouldn't be behaving any differently. The first argument for get_post_meta() needs to be a post ID. How to get that depends on the context. May 11, 2018 at 13:42
  • My bad, I had misplaced the code in my file. thank you again !
    – Garrosh
    May 11, 2018 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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