You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在WP_Query中添加分类法作为查询参数?

How to Add Toolset Taxonomy Filter to WP_Query for Custom Post Types

Hey there! I see you're using Toolset to build custom taxonomies and post types in WordPress, and you want to filter your product posts by their product_category taxonomy within a WP_Query. Let's break down how to solve this and walk through the key changes.

The Issue in Your Initial Code

Your original WP_Query arguments didn't include any taxonomy filtering logic, so it was pulling all published product posts instead of only those linked to the current category you're looping through.

The Fix: Add tax_query to Your WP_Query Arguments

The critical addition here is the tax_query parameter—WordPress's built-in way to filter posts by taxonomy terms. Here's how you implemented it in your working code, plus a breakdown of each component:

Key Updated Code Section

// args
$args = array(
    'posts_per_page' => 5,
    'post_type' => 'product',
    'post_status' => 'publish',
    'tax_query' => array(
        array (
            'taxonomy' => 'product_category',
            'field' => 'name',
            'terms' => $ir, // $ir is set to $taxonomy->name earlier in the loop
        )
    ),
);
// query
$the_query = new WP_Query( $args );

What Each tax_query Parameter Does

  • taxonomy: This is the slug of your Toolset-created taxonomy, matching what you used in get_terms() (product_category).
  • field: Defines which term field you want to match against. You used name here because you assigned $taxonomy->name to $ir. For more reliability (term names can be duplicated, but IDs can't), you could switch this to term_id and use $taxonomy->term_id directly.
  • terms: The specific term you want to filter by—either the name or ID of the current product_category term in your loop.

Full Working Code Context

Here's the complete updated code that correctly filters posts for each top-level product_category:

<?php $taxonomies = get_terms([ 
    'taxonomy' => 'product_category', 
    'parent' => 0, 
    'orderby' => 'name', 
    'order' => get_query_var('Order', 'ASC'), 
    'hide_empty' => false, 
]); ?>
<?php $i=1; if ($taxonomies) { foreach ($taxonomies as $taxonomy ) {; ?>
    <?php if(!empty(do_shortcode('[types term_id="'.$taxonomy->term_id.'" termmeta="secondary-category-image" size="product-main-cat" url="true"][/types]'))){ 
        $pro_cat_img = do_shortcode('[types term_id="'.$taxonomy->term_id.'" termmeta="secondary-category-image" size="product-main-cat" url="true"][/types]'); 
    }else{ 
        $pro_cat_img = get_template_directory_uri()."/img/product-guitar.png"; 
    } ?>
    <div class="product-row clearfix">
        <div class="bg-box">
            <?php if($i==1){?>
                <img src="<?php echo esc_url($pro_cat_img); ?>" class="product-guitar"/>
            <?php }else if($i==2){ ?>
                <img src="<?php echo esc_url($pro_cat_img); ?>" class="product-speaker"/>
            <?php }else if($i==3){ ?>
                <img src="<?php echo esc_url($pro_cat_img); ?>" class="product-headphone"/>
            <?php } ?>
            <a href="<?php echo esc_url( add_query_arg( array('cat'=>$taxonomy->term_id), home_url('/products') ) ); ?>" class="view-more-btn button button--moema "> READ MORE </a>
        </div>
        <div class="items-list-box">
            <h1> <?php echo $taxonomy->name; $ir=$taxonomy->name; ?> </h1>
            <ul>
                <?php 
                // args
                $args = array(
                    'posts_per_page' => 5,
                    'post_type' => 'product',
                    'post_status' => 'publish',
                    'tax_query' => array(
                        array (
                            'taxonomy' => 'product_category',
                            'field' => 'name',
                            'terms' => $ir,
                        )
                    ),
                );
                // query
                $the_query = new WP_Query( $args );
                $count = $the_query->post_count;
                if( $the_query->have_posts() ): 
                    while( $the_query->have_posts() ) : $the_query->the_post();
                        if(has_post_thumbnail(get_the_ID())) { 
                            $feature_image_full = simplexml_load_string(get_the_post_thumbnail(get_the_ID(), 'banner_img')); 
                            $pr_img_source = $feature_image_full->attributes()->src; ?>
                            <li> <span> <?php echo the_title(); ?> </span> </li>
                        <?php } 
                    endwhile; 
                endif; 
                wp_reset_query(); ?>
            </ul>

Quick Optimization Tip

Using term_id instead of name in your tax_query is a safer practice because term names aren't unique (you could accidentally create two categories with the same name), but term IDs are always unique. To make this switch, update these lines:

// Remove the $ir assignment in the h1 section
<h1> <?php echo $taxonomy->name; ?> </h1>

// Update the tax_query to use term_id
'tax_query' => array(
    array (
        'taxonomy' => 'product_category',
        'field' => 'term_id',
        'terms' => $taxonomy->term_id,
    )
),

That's all! This ensures your WP_Query only pulls posts that belong to the current product_category term you're displaying.

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

火山引擎 最新活动