【问题标题】:WordPress: How to filter posts by category using $wp_query?WordPress:如何使用 $wp_query 按类别过滤帖子?
【发布时间】:2017-06-12 16:41:41
【问题描述】:

我在 WordPress 上构建了一个带有静态首页的自定义主题,并且在 设置>阅读设置>首页显示中没有设置页面作为帖子页面。但是,我想在整个站点的不同静态页面上根据它们的类别显示帖子。因此,我永远不会通过控制台声明帖子索引页面。所以我使用了 $wp_query 函数。

如何向这个脚本添加一个过滤器,只显示“苹果”类别的帖子(例如)?目前,此脚本会显示所有帖子,无论类别如何。

<?php
    $temp = $wp_query;
    $wp_query = null;
    $wp_query = new WP_Query();
    $wp_query->query('showposts=1' . '&paged='.$paged);
    while ($wp_query->have_posts()) : $wp_query->the_post();
?>

<h2><a href="<?php the_permalink(); ?>" title="Read"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php the_date(); ?>

<?php endwhile; ?>

<?php if ($paged > 1) { ?>
    <p><?php previous_posts_link('Previous page'); ?>
    <?php next_posts_link('Next page'); ?></p>
<?php } else { ?>
    <p><?php next_posts_link('Next page'); ?></p>
<?php } ?>

<?php wp_reset_postdata(); ?>

【问题讨论】:

    标签: php wordpress custom-post-type posts


    【解决方案1】:

    您必须使用 category_name(字符串 - 使用类别 slug)或 cat (int - 使用类别 id),按类别获取 WP_Query::query() 中的帖子。

    这是一个例子:

    $category_name = 'apples'; //replace it with your category slug
    $temp = $wp_query;
    $wp_query = null;
    $wp_query = new WP_Query();
    $wp_query->query('showposts=1' . '&paged=' . $paged . '&category_name=' . $category_name);
    //...
    //...
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      删除你的第一个 php 块并用这个替换它

      <?php
      $args = array (
          'showposts' => '1',
          'category_name' => 'apples',
          'paged' => $paged
      );
      $the_query = new WP_Query( $args );
      
      if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
      ?>
      

      更多信息https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-23
        • 2020-11-10
        相关资源
        最近更新 更多