【问题标题】:wordpress - display list of posts excluding a specific tagwordpress - 显示不包括特定标签的帖子列表
【发布时间】:2015-01-09 01:50:12
【问题描述】:

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

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


    【解决方案1】:

    您将不得不在这里使用tax_query 来完成这项工作。普通的标签参数无法胜任。

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

    • showposts 折旧以支持posts_per_page

    • numberpostsWP_Query 中无效

    • wp_reset_postdata() 用于WP_Querywp_reset_query() 与永远不应该使用的query_posts 一起使用

    • 您需要在endif 之前调用wp_reset_postdata(),就在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 );
    

    【讨论】:

      【解决方案2】:

      您可以使用 tag__not_in 参数 (see here),但您需要 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();                     
      
      ?>
      

      【讨论】:

      • 我不认为numberposts 是一个有效的参数,可能需要删除它。
      猜你喜欢
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多