简体   繁体   中英

How to determine category name of returned Posts in WordPress

What i'm trying to do is find out what category the Posts are when they are returned so i can put them in specific divs.

eg i have #div1 #div2 and #div3 and i have 3 posts returned each with a different category.

What i want to do is have 1 post each in a div . To do this i need to determine the category.

Here is how i fetch Posts by category but how do i fetch Posts of 3 categories and determine the category of the Posts returned, so i can change the div id?

<?php
//gallery
$args = array( 'category_name' => 'Clubs');
$postslist = get_posts( $args );

foreach ( $postslist as $post ) :
setup_postdata( $post );
?>

<div id="div1">
<?php the_content(); ?>   
</div>

<?php
endforeach; 
wp_reset_postdata();
?>

Obviously i could duplicate this code twice and just change the category and div names but is that the right way to do this?

To avoid copy-paste, I'd suggest putting your code in a function, which takes the parts you want to change as parameters. Something like this (I added the posts_per_page parameter, since you said you only want one post per div):

<?php
function show_gallery($category, $id) {

    $args = array( 'category_name' => $category, 'posts_per_page' => 1);
    $postslist = get_posts( $args );

    foreach ( $postslist as $post ) :
    setup_postdata( $post );
    ?>

    <div id="div<?php echo $id; ?>">
        <?php the_content(); ?>   
    </div>

    <?php
    endforeach; 
    wp_reset_postdata();
}

show_gallery('Clubs', 1);
show_gallery('Hearts', 2);
show_gallery('Diamonds', 3);
?>

I haven't tested, but hopefully it works and is enough to get you started.

I'd put the function declaration at the top of your template.

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