0

0 down vote favorite I have a page showing your typical series of small post teasers - images, excerpt etc which advertise properties for lease.

I would like to have the ability to add a 'new' or 'featured' icon based on its corresponding 'new' or 'featured' category or tag - either will do.

I have added these categories but they do not appear in the code when output and so I cannot target them.

How would I be able to perform the action:

If a post thumbnail has category of 'new' add the class 'new' so I can then target and style - repeating for each category.

I found this below which I think is similar but does not work

There will be multiple categories displaying on the archive page, but I want to style only the previews that have a certain category - I do not want to style the individual post page.

Unfortunately my php skills are limited

Thanks

$post = $wp_query->post;

if ( in_category('new', $post->ID) ) { ?>
    <body <?php body_class('new'); ?>> 
<?php
} 

elseif ( in_category('featured', $post->ID) ) { ?>
    <body <?php body_class('featured'); ?>> 
<?php
} 

else { ?>
    <body <?php body_class('class-name-generic'); ?>>
<?php
    }
?>

1 Answer 1

0

This sounds like something that should go to the The Loop - you want this class per post, not for the whole <body>, right? Roughly archive.php (or index.php, or category-*.php) should look like this:

while (have_posts()) {
    the_post();
    $add_class = array();
    if (in_category('new')) { // inside the loop, don't need $post->ID
        $add_class[] = 'new';
    if (in_category('featured'))
        $add_class[] = 'featured'; // and so on
    ?>
    <article <?php post_class($add_class); ?>>
    <?php // ...
}

Or, depending on the theme, in content.php or some version thereof. See docs for post_class.

2
  • Unfortunately I can't get this to work. I pasted it in all the suggested php templates I have discovered that the php template outputting the post grid is a visual composer php file, I tried in there too but not such luck.
    – Mr Toad
    Commented Dec 10, 2018 at 23:03
  • But please don't paste it verbatim, this is just a guideline! You could try and show the relevant code here, but the Visual Composers and Pagebuilders I've seen can have a complex, convoluted and sometimes messy code...
    – kubi
    Commented Dec 11, 2018 at 9:47

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.