Php 获取Woocommerce中特定产品类别的特定产品属性值

Php 获取Woocommerce中特定产品类别的特定产品属性值,php,wordpress,woocommerce,product,custom-taxonomy,Php,Wordpress,Woocommerce,Product,Custom Taxonomy,我已经通过以下代码获得了所有颜色属性: $color_terms = get_terms( array( 'taxonmy'=>'pa_color' )); 这适用于商店页面并返回所有颜色,但如何将其限制为特定类别?假设在一个名为“衬衫”的类别中,我只有两种颜色,我只想显示这两种颜色 尝试使用唯一的light SQL查询的以下自定义函数: function get_attribute_terms_in_product_cat( $category_

我已经通过以下代码获得了所有颜色属性:

$color_terms = get_terms(
        array(
        'taxonmy'=>'pa_color'
    ));

这适用于商店页面并返回所有颜色,但如何将其限制为特定类别?假设在一个名为“衬衫”的类别中,我只有两种颜色,我只想显示这两种颜色

尝试使用唯一的light SQL查询的以下自定义函数:

function get_attribute_terms_in_product_cat( $category_term_name, $attribute_taxonomy ){
    global $wpdb;

    $terms = $wpdb->get_results( "SELECT DISTINCT t.*
        FROM {$wpdb->prefix}terms as t
        JOIN {$wpdb->prefix}term_taxonomy as tt ON tt.term_id = t.term_id
        JOIN {$wpdb->prefix}term_relationships as tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
        WHERE tt.taxonomy LIKE '$attribute_taxonomy'
        AND tr.object_id IN ( SELECT DISTINCT tr2.object_id
            FROM {$wpdb->prefix}term_relationships as tr2
            JOIN {$wpdb->prefix}term_taxonomy as tt2 ON tt2.term_taxonomy_id = tr2.term_taxonomy_id
            JOIN {$wpdb->prefix}terms as t2 ON tt2.term_id = t2.term_id
            WHERE tt2.taxonomy LIKE 'product_cat' AND t2.name = '$category_term_name'
        )" );

    return $terms;
}
代码进入活动子主题(或活动主题)的function.php文件。测试和工作


用法

// Get the "pa_color" attribute terms for product category "Shirts"
$terms = get_attribute_terms_in_product_cat( "Shirts", "pa_color" );
这里,“衬衫”是一个产品类别术语名称,“颜色”产品属性分类法

您将获得一个产品属性值数组(术语对象),其中包含:

  • 术语ID(键
    术语ID
  • 术语名称(键
    名称
  • 术语slug(键
    slug
可以使用foreach循环访问每个术语对象:

// Get the "pa_color" attribute terms for product category "Shirts"
$terms = get_attribute_terms_in_product_cat( "Shirts", "pa_color" );

// Loop through each term
foreach( $terms as $term ){
    $term_id   = $term->term_id;
    $term_name = $term->name;
    $term_slug = $term->slug;
}