如何检查 post 是否属于两个给定类别

How to check if a post is in two given categories

我有一个名为 news 和 featured post 的类别。我想显示 post 是否同时出现在新闻和精选中-post.

$args = array('category_name' => 'news','featured-post','posts_per_page'=>1);

$lastposts = get_posts( $args );
foreach ( $lastposts as $post ) : setup_postdata( $post ); 

如有任何帮助,我们将不胜感激。

如果您未绑定到 get_posts,您可以使用 WP_Querycategory__and(注意双下划线!)到 return 帖子,这些帖子分为两个 (或更多)类别。

$args = array('category__and' => array(1, 2));
$result = new WP_Query($args);
while($result->have_posts())
{
   // do whatever you want
}

我无法帮助您使用 get_posts

不过,您可以按照 Display posts that have "all" of these categories:

下的 wordpress' documentation 中所述,使用 WP_Query 进行尝试
$args = array(
    'posts_per_page' => 1,
    'category_name=news+featured-post' );
);

$my_query = new WP_Query( $args );
while( $my_query->have_posts() ):
    $my_query->the_post();
    //do things with the post
endwhile;

wp_reset_postdata();