Skip to content

Instantly share code, notes, and snippets.

@mehrshaddarzi
Created June 23, 2024 17:24
Show Gist options
  • Save mehrshaddarzi/ddfd1a57fa9e8609add2986927bba91b to your computer and use it in GitHub Desktop.
Save mehrshaddarzi/ddfd1a57fa9e8609add2986927bba91b to your computer and use it in GitHub Desktop.
Get All Product Attributes by Category Slug WooCommerce
<?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