首页 文章

WordPress:如何使用$ wp_query按类别过滤帖子?

提问于
浏览
2

我在WordPress上构建了一个自定义主题,其中包含静态首页,并且在 Settings > Reading Settings > Front page displays 中没有设置页面作为帖子页面 . 我想根据不同静态页面上整个网站的类别来显示帖子 . 因此,我永远不会通过控制台声明帖子索引页面 . 所以我使用$ wp_query函数 .

如何在此脚本中添加过滤器,仅显示“apples”类别中的帖子(例如)?现在,此脚本显示所有帖子,无论类别如何 .

<?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(); ?>

2 回答

  • 5

    您必须使用category_name(string - use category slug)或cat(int - use category 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);
    //...
    //...
    

    希望这可以帮助!

  • 4

    删除你的第一个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

相关问题