Woocommmerce. Нужно вывести все метки, относящиеся к конкретной категории
Всем привет! Возникла проблема при выводе меток для всех категорий. Есть код, но он выводит метки для текущего товара:
function woocom_tags_list(){
$output = array();
// get an array of the WP_Term objects for a defined product ID
$terms = wp_get_post_terms( get_the_id(), 'product_tag' );
// Loop through each product tag for the current product
if( count($terms) > 0 ){
foreach($terms as $term){
$term_id = $term->term_id; // Product tag Id
$term_name = $term->name; // Product tag Name
$term_slug = $term->slug; // Product tag slug
$term_link = get_term_link( $term, 'product_tag' ); // Product tag link
// Set the product tag names in an array
$output[] = '<a href="'.$term_link.'">'.$term_name.'</a>';
}
// Set the array in a coma separated string of product tags for example
$output = implode( ', ', $output );
// Display the coma separated string of the product tags
return $output;
}
}
У меня есть id категории, нужно вывести все метки для нее и дочерних категорий. Как это можно сделать?
Ответы (1 шт):
Автор решения: WP Punk
→ Ссылка
function get_terms_in_term( int $term_id, string $term_slug, string $child_term_slug ) {
global $wpdb;
$key = 'child_' . $child_term_slug . '_by_' . $term_id;
$terms = wp_cache_get( $key );
if ( ! empty( $terms ) ) {
return $terms;
}
//phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$terms = $wpdb->get_results(
$wpdb->prepare(
'SELECT DISTINCT t.term_id as term_id, t.name as name
FROM ' . $wpdb->terms . ' as t
LEFT JOIN ' . $wpdb->term_taxonomy . ' as tt ON t.term_id = tt.term_taxonomy_id
LEFT JOIN ' . $wpdb->term_relationships . ' as r ON t.term_id = r.term_taxonomy_id
WHERE tt.taxonomy = %s
AND r.object_id IN (
SELECT DISTINCT p.ID
FROM ' . $wpdb->posts . ' as p
LEFT JOIN ' . $wpdb->term_relationships . ' as r2 ON p.ID = r2.object_id
LEFT JOIN ' . $wpdb->term_taxonomy . ' as t2 ON t2.term_id = r2.term_taxonomy_id
WHERE p.post_type = "product"
AND p.post_status = "publish"
AND t2.taxonomy = %s
AND t2.term_id = %d
)
ORDER BY name',
$child_term_slug,
$term_slug,
$term_id
)
);
if ( $terms ) {
foreach ( $terms as $key => $term ) {
$terms[ $key ]->url = get_term_link( $term->term_id );
}
wp_cache_set( 'child_' . $child_term_slug . '_by_' . $term_id, $terms );
}
return $terms;
}
$terms = get_terms_in_term( 55, 'product_cat', 'product_tag' );