You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress如何按指定分类查询页面并实现分类筛选功能

问题原因

get_pages() 函数原生不支持category_name参数,你传入的分类过滤条件没有被识别,所以会输出所有页面。另外原代码中容器闭合标签放在了循环内部,会导致HTML结构错乱。

修复基础分类过滤

优先使用WP_Query实现,对分类参数的支持更稳定:

<div class="container">
<div class="row">
<?php
$args = array(
    'post_type' => 'page',
    'posts_per_page' => -1,
    'category_name' => 'category1,category2', // 逗号前后不要留空格
    'post_status' => 'publish'
);
$custom_query = new WP_Query($args);

if($custom_query->have_posts()) :
    while($custom_query->have_posts()) : $custom_query->the_post();
?>
    <div class="col">
        <a href="<?php the_permalink(); ?>" class="header-link"><?php the_title(); ?></a>
        <?php echo get_the_post_thumbnail(get_the_ID(), 'thumbnail'); ?>
    </div>
<?php
    endwhile;
    wp_reset_postdata(); // 重置查询避免影响全局逻辑
endif;
?>
</div>
</div>

如果要继续使用get_pages(),需要改为传入分类法查询参数:

$pages = get_pages(array(
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => array('category1', 'category2')
        )
    )
));

实现点击分类筛选功能

先在页面顶部添加分类切换导航,通过URL参数传递筛选条件:

<!-- 分类筛选导航 -->
<div class="category-filter">
    <a href="<?php echo get_permalink(); ?>" class="filter-item <?php echo !isset($_GET['filter_cat']) ? 'active' : ''; ?>">全部</a>
    <a href="<?php echo add_query_arg('filter_cat', 'category1', get_permalink()); ?>" class="filter-item <?php echo (isset($_GET['filter_cat']) && $_GET['filter_cat'] === 'category1') ? 'active' : ''; ?>">分类1</a>
    <a href="<?php echo add_query_arg('filter_cat', 'category2', get_permalink()); ?>" class="filter-item <?php echo (isset($_GET['filter_cat']) && $_GET['filter_cat'] === 'category2') ? 'active' : ''; ?>">分类2</a>
</div>

再修改查询逻辑,动态匹配筛选的分类:

<?php
// 接收并过滤分类参数
$filter_cat = isset($_GET['filter_cat']) ? sanitize_text_field($_GET['filter_cat']) : '';
$target_terms = $filter_cat ? array($filter_cat) : array('category1', 'category2');

$args = array(
    'post_type' => 'page',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => $target_terms
        )
    ),
    'post_status' => 'publish'
);
$custom_query = new WP_Query($args);
// 后续循环渲染逻辑和上文一致即可
?>

可以给.active类加样式区分当前选中的分类。

内容的提问来源于stack exchange,提问作者GiulyM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 12:21:03