简体   繁体   English

获取 WooCommerce 中产品的所有“活跃”属性分类法?

[英]Get all “active” attributes taxonomies attached to products in WooCommerce?

I want to get all "active" attributes list that attached to the products,我想获取附加到产品的所有“活动”属性列表,

so if the attribute exists, but don't attach to any products don't display.因此,如果该属性存在,但不附加到任何产品不显示。

I can display all attributes as dropdown like this:我可以像这样将所有属性显示为下拉列表:

$attributes =  wc_get_attribute_taxonomies();

if($attributes) {
    echo '<select name="all-attributes" id="all-attributes">';
    foreach ( $attributes as $attribute ) {
        echo '<option value="' . $attribute->attribute_name . '">' . $attribute->attribute_label . '</option>';
    }
    echo '</select>';
}

But this way I'm getting all attributes, even non active attributes is not attached.但是这样我得到了所有属性,即使是非活动属性也没有附加。

How to get all active product attributes taxonomies attached to products in WooCommerce?如何获取 WooCommerce 中产品的所有活动产品属性分类法?

To get all active product attributes taxonomies (attached a least to a product) you will need a custom simple sql query as follow (embedded in a php function) :要获得所有有效的产品属性分类法(至少附加到产品上) ,您需要一个自定义的简单 sql 查询,如下所示(嵌入在 php 函数中)

function wc_get_active_attribute_taxonomies() {
    global $wpdb;

    return $wpdb->get_results( "
        SELECT DISTINCT  wat.*, tt.taxonomy
        FROM {$wpdb->prefix}woocommerce_attribute_taxonomies wat
        INNER JOIN {$wpdb->prefix}term_taxonomy tt
            ON tt.taxonomy = CONCAT('pa_', wat.attribute_name)
        INNER JOIN {$wpdb->prefix}term_relationships tr
            ON tt.term_taxonomy_id = tr.term_taxonomy_id
        WHERE tt.count > 0
    " );
}

Code goes in functions.php file of your active child theme (or active theme).代码进入您的活动子主题(或活动主题)的functions.php 文件。 Tested and works.测试和工作。


USAGE (based on your code) :用法(基于您的代码)

Just replace:只需更换:

$attributes = wc_get_attribute_taxonomies();

by:经过:

$attributes = wc_get_active_attribute_taxonomies();

Note: This query output, includes additionally the "taxonomy" argument.注意:此查询 output 还包括“分类”参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM