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

修改Elementor Pro查询:按自定义分类法展示文章

解决Elementor Pro Post Widget按自定义分类法筛选文章的问题

你当前的代码仅能调用WordPress默认的「标签」分类法,要适配自定义分类法,需修改两处核心逻辑:替换获取分类项的函数,改用tax_query指定自定义分类法的筛选规则。

修改后的完整代码

add_action( 'elementor/query/limitpost', function( $query ) {
    // 替换成你自己的自定义分类法slug(即Custom Post Type UI里设置的分类法别名)
    $custom_taxonomy = 'your_custom_taxonomy';
    
    // 获取当前文章关联的自定义分类项
    $tax_objects = get_the_terms( get_the_ID(), $custom_taxonomy );
    $tax_slugs = [];
    
    if ( $tax_objects && ! is_wp_error( $tax_objects ) ) {
        foreach( $tax_objects as $temp_tax ) {
            $tax_slugs[] = $temp_tax->slug;
        }
    }

    // 仅当存在分类项时设置筛选规则
    if ( ! empty( $tax_slugs ) ) {
        $query->set( 'tax_query', [
            [
                'taxonomy' => $custom_taxonomy,
                'field'    => 'slug',
                'terms'    => $tax_slugs,
            ],
        ] );
    }

    // 保留原有基础设置
    $query->set( 'post_type', 'post' ); // 若需展示自定义文章类型,把这里的post换成对应slug
    $query->set( 'post_status', 'publish');
    $query->set( 'order', 'DESC');
    $query->set( 'orderby', 'date' );
} );

关键操作指引(照做即可)

  1. 替换分类法slug:找到你在Custom Post Type UI里创建的自定义分类法的「别名(slug)」,把代码里的'your_custom_taxonomy'替换成这个值。比如你创建的分类法叫「产品分类」,slug可能是product_category,就改成'product_category'。
  2. 适配自定义文章类型(可选):如果Post Widget要展示的不是WordPress默认的「文章(post)」,而是你创建的自定义文章类型,把'post_type', 'post'里的post换成该自定义文章类型的slug。

使用步骤

  1. 添加代码:推荐用「Code Snippets」插件新建代码片段,粘贴修改后的代码后启用;也可添加到当前主题的functions.php文件末尾(操作前建议备份主题文件)。
  2. 验证设置:回到Elementor的Post Widget配置,确保「查询ID」仍为limitpost,保存页面后即可生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 02:23:23