简体   繁体   English

如何确定WordPress中返回的帖子的类别名称

[英]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. 我正在尝试做的是找出帖子归还时的类别,这样我就可以将它们放在特定的div中。

eg i have #div1 #div2 and #div3 and i have 3 posts returned each with a different category. 例如,我有#div1 #div2#div3 ,我有3个帖子,每个帖子都有不同的类别。

What i want to do is have 1 post each in a div . 我想做的是每个div有1个帖子。 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? 这是我按类别提取帖子的方式,但是如何获取3个类别的帖子并确定返回的帖子的类别,因此我可以更改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? 显然,我可以重复两次此代码,只是更改类别和div名称,但这是正确的方法吗?

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): 这样的事情(我添加了posts_per_page参数,因为您说过每个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. 我将函数声明放在模板的顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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