简体   繁体   中英

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?

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) :

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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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