问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/61952878/get-all-active-attributes-taxonomies-attached-to-products-in-woocommerce