【问题标题】:Get all "active" attributes taxonomies attached to products in WooCommerce?获取附加到 WooCommerce 中产品的所有“活动”属性分类法?
【发布时间】:2020-09-09 04:01:26
【问题描述】:

我想获取附加到产品的所有“活动”属性列表,

所以如果该属性存在,但不附加到任何产品不显示。

我可以像这样将所有属性显示为下拉列表:

$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>';
}

但是这样我得到了所有属性,即使是非活动属性也没有附加。

如何在 WooCommerce 中获取附加到产品的所有活跃产品属性分类法?

【问题讨论】:

    标签: php sql wordpress woocommerce custom-taxonomy


    【解决方案1】:

    要获得所有活动产品属性分类法(至少附加到产品上)您将需要一个自定义的简单 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
        " );
    }
    

    代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。


    用法 (根据您的代码)

    只需替换:

    $attributes = wc_get_attribute_taxonomies();
    

    作者:

    $attributes = wc_get_active_attribute_taxonomies();
    

    注意:此查询输出还包括“分类”参数。

    【讨论】:

    • 谢谢,但我将此代码插入钩子操作 woocommerce_before_shop_loop 并仅获取第一个属性及其条款。我做错了什么?
    • 我想你不明白我的意思。我的意思是我想显示所有“活跃”的属性,这有意义吗?
    • @AkForDev 或者你也可以通过我的个人资料推特链接给我发私信
    • 明天我会在您的联系表格中给您写信
    猜你喜欢
    • 2020-08-21
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 2017-06-26
    • 2018-10-11
    • 2019-09-03
    • 1970-01-01
    • 2021-05-22
    相关资源
    最近更新 更多