简体   繁体   中英

Style post archive blog preview based on category

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 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
    }
?>

here you go get_the_category($post->ID); will return the array of categories of that post you need to loop through the array

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM