Created
June 23, 2024 17:24
-
-
Save mehrshaddarzi/ddfd1a57fa9e8609add2986927bba91b to your computer and use it in GitHub Desktop.
Get All Product Attributes by Category Slug WooCommerce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_attributes_by_product_cat($category_slug = null, $cacheHour = 6) | |
{ | |
global $wpdb; | |
// Check Product Cat Slug | |
if (is_null($category_slug)) { | |
$query_object = get_queried_object(); | |
$category_slug = $query_object->slug ?? ''; | |
} | |
// Check Empty Slug | |
if (empty($category_slug)) { | |
return []; | |
} | |
// Check Cache | |
$option = get_option('attributes_' . md5($category_slug), []); | |
if (is_array($option) and isset($option['data']) and isset($option['expire']) and $option['expire'] > current_time('timestamp')) { | |
return $option['data']; | |
} | |
// Setup Query | |
$terms = $wpdb->get_results("SELECT t.name as taxonomy_name,tr.object_id, tt.taxonomy, tt.term_id, t.name, count(*) as count | |
FROM {$wpdb->prefix}term_relationships AS tr | |
JOIN {$wpdb->prefix}term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id | |
JOIN {$wpdb->prefix}terms AS t ON tt.term_id = t.term_id | |
WHERE tr.object_id IN ( | |
SELECT p.ID | |
FROM {$wpdb->prefix}posts AS p | |
JOIN {$wpdb->prefix}term_relationships AS tr ON p.ID = tr.object_id | |
JOIN {$wpdb->prefix}term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id | |
JOIN {$wpdb->prefix}terms AS t ON tt.term_id = t.term_id | |
WHERE p.post_type = 'product' | |
AND p.post_status = 'publish' | |
AND tt.taxonomy = 'product_cat' | |
AND ('$category_slug'='' OR t.slug = '$category_slug') | |
) | |
AND tt.taxonomy LIKE 'pa_%' | |
GROUP By tt.term_id"); | |
// Prepare filters | |
$filters = []; | |
foreach ($terms as $term) { | |
if (!isset($filters[$term->taxonomy])) { | |
$filters[$term->taxonomy] = array( | |
'name' => wc_attribute_label($term->taxonomy), | |
'count' => 0, | |
'options' => [] | |
); | |
} | |
$filters[$term->taxonomy]['count'] += $term->count; | |
$filters[$term->taxonomy]['options'][] = array( | |
'term_id' => $term->term_id, | |
'name' => $term->name, | |
'count' => $term->count, | |
); | |
} | |
// Setup Cache | |
update_option('attributes_' . md5($category_slug), [ | |
'data' => $filters, | |
'expire' => current_time('timestamp') + (HOUR_IN_SECONDS * $cacheHour) | |
], 'no'); | |
// Return | |
return $filters; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
related:
https://stackoverflow.com/questions/52572687/get-all-attributes-with-their-terms-related-to-a-product-category-in-woocommerce