在Woocommerce 3.3中为产品简码使用自定义分类法 [英] Using a custom taxonomy for products shortcode in Woocommerce 3.3
问题描述
我目前正在为Woocommerce网站开发主页,在此页面上,目标是使3行显示来自不同品牌的产品。例;第1行将显示Apple产品,第2行将显示Samsung产品,第3行将显示HTC产品。
I'm currently developing the homepage for a Woocommerce website and on this page the goal is to have 3 rows displaying products from different brands. Example; Row 1 will display Apple Products, Row 2 will display Samsung Products and Row three will display HTC products.
我已经使用插件CPT UI创建自定义分类法'牌'。现在,我希望使用上面的示例仅显示特定品牌下列出的产品。
I've used the plugin CPT UI to create the custom taxonomy 'Brand'. Now I wish to use the example above to display only products listed under a particular brand.
查看Woocommerce简码,我看到了:
Looking into the Woocommerce Shortcodes, I saw this:
[products limit="8" columns="4" category="hoodies, tshirts" cat_operator="AND"]
是否有针对此案例品牌的自定义分类法来执行类似的操作? IE:
Is there away to do something like this with a custom taxonomy for this case brands? I.E:
[products limit="8" columns="4" brand="apple" cat_operator="AND"]
任何朝着正确方向提供帮助或推动的人都将受到赞赏!
Any assistance or nudges in the right direction are much appreciated!
推荐答案
可以将Woocommerce [产品]
短代码扩展为处理任何自定义分类法,例如 品牌
,并带有某种技巧。
It's possible to extend Woocommerce [products]
shortcode to To handle any custom taxonomy like "brand"
with some kind of trick.
代码:
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文件)。经过测试和工作。
Code goes in function.php file of your active child theme (or active theme). Tested and works.
使用情况
我们将在此处使用类
简码参数:
We will use the class
shortcode argument here:
1)一个品牌-显示 Apple品牌的产品:
1) One Brand - Displaying products from "Apple" brand:
[products limit="8" columns="4" class="brand,Apple"]
2)多个品牌-显示 Apple的产品和三星品牌:
2) multiple Brands - Displaying products from "Apple" and "Samsung" brands:
[products limit="8" columns="4" class="brand,Apple,Samsung"]
所以类
品牌
是强制性的,必须是第一个。每个词都用逗号分隔。
So the class
"brand"
is mandatory and needs to be the first one. Each term is coma separated.
这篇关于在Woocommerce 3.3中为产品简码使用自定义分类法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!