可以扩展 Woocommerce[products]
短代码来处理任何自定义分类法,例如"brand"
用某种技巧。
代码:
add_filter( 'woocommerce_shortcode_products_query', 'extend_products_shortcode_to_brand', 10, 3 );
function extend_products_shortcode_to_brand( $query_args, $atts, $loop_name ){
if ( ! empty($atts['class']) && strpos($atts['class'], 'brand') !== false ) {
global $wpdb;
$terms = array_map( 'sanitize_title', explode( ',', $atts['class'] ) );
array_shift( $terms );
$terms = implode(',', $terms);
$terms = str_replace(",", "','", $terms);
$ids = $wpdb->get_col( "
SELECT DISTINCT tr.object_id
FROM {$wpdb->prefix}term_relationships as tr
INNER JOIN {$wpdb->prefix}term_taxonomy as tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN {$wpdb->prefix}terms as t ON tt.term_id = t.term_id
WHERE tt.taxonomy LIKE 'brand' AND t.slug IN ('$terms')
" );
if ( ! empty( $ids ) ) {
if ( 1 === count( $ids ) ) {
$query_args['p'] = $ids[0];
} else {
$query_args['post__in'] = $ids;
}
}
}
return $query_args;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。
USAGE
我们将使用class
此处的简码参数:
1) 单一品牌- 展示“Apple”品牌的产品:
[products limit="8" columns="4" class="brand,Apple"]
2) 多个品牌- 展示“Apple”和“Samsung”品牌的产品:
[products limit="8" columns="4" class="brand,Apple,Samsung"]
所以班级"brand"
是强制性的,并且需要是第一个。每个术语均以逗号分隔。