wordpress - 显示不包括特定标签的帖子列表

问题描述 投票:0回答:2

我想显示具有特定标签但没有其他特定标签的帖子列表。例如,我尝试以下方法来显示具有“动物”标签的帖子列表。

<?php 
    $args = array(
        'numberposts' => 1,
        'tag' => 'animal',
        'showposts' => 8
         );
    $query = new WP_Query($args);
    if($query->have_posts()):
        echo '<table>';
        while($query->have_posts()): $query->the_post();
             the_title(); ?> </a></td>

        endwhile;

    endif;
    wp_reset_query();                     

?>

我们如何在“动物”标签中显示帖子列表,但不在“猫”标签中显示? 我对 WordPress 非常陌生,刚刚学会创建自定义页面。

php wordpress tags
2个回答
2
投票

您将必须使用

tax_query
才能完成这项工作。普通的标签参数无法完成这项工作。

只是对原始代码的一些注释

  • showposts
    已贬值,有利于
    posts_per_page

  • numberposts
    WP_Query

  • 中无效
  • 使用

    wp_reset_postdata()
    代替
    WP_Query
    wp_reset_query()
    query_posts
    一起使用,切勿使用

  • 您需要在

    wp_reset_postdata()
    之后
    endif
     之前致电 

    endwhile

你需要这样的东西

$args = array(
    'posts_per_page' => '8',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'slug', //Can use 'name' if you need to pass the name to 'terms
            'terms'    => 'animal', //Use the slug of the tag
        ),
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'slug',
            'terms'    => 'cat',
            'operator' => 'NOT IN',
        ),
    ),
);
$query = new WP_Query( $args );

1
投票

您可以使用

tag__not_in
参数(参见此处),但您需要 cat 标签的 term_id。所以也许是这样的:

<?php 
// get term_id of unwanted cat tag for tag__not_in param
$tag = get_term_by('name', 'cat', 'post_tag');

$args = array(
    'numberposts' => 1,
    'tag_slug__in' => array('animal'),
    'tag__not_in' => array($tag->term_id),
    'showposts' => 8
     );

$query = new WP_Query($args);
if($query->have_posts()):
    echo '<table>';
    while($query->have_posts()): $query->the_post();
         the_title(); ?> </a></td>

    endwhile;

endif;
wp_reset_query();                     

?>
© www.soinside.com 2019 - 2024. All rights reserved.