我使用 2 个短代码 [品牌名称] 和 [产品名称] 在产品单一模板上显示子分类术语和孙分类术语。
示例 1:智能手机 > Apple > iPhone 14
示例2:平板电脑 > Apple > iPad Pro 12.9 英寸(第 5 代)
示例 1 短代码效果很好 示例 2 短代码没有,两个短代码都显示孙分类术语。
代码:
/**
* Brandname for Product Single Page shortcode
*/
function child_category_shortcode($atts) {
global $post;
$product_terms = get_the_terms($post->ID, 'product_cat');
if (!empty($product_terms)) {
foreach ($product_terms as $term) {
if ($term->parent != 0) {
return $term->name;
}
}
}
}
add_shortcode('brandname', 'child_category_shortcode');
/**
* Productname for Product Single Page shortcode
*/
function grandchild_category_shortcode($atts) {
global $post;
$product_terms = get_the_terms($post->ID, 'product_cat');
if (!empty($product_terms)) {
foreach ($product_terms as $term) {
$parent_id = $term->parent;
if ($parent_id != 0) {
$parent_term = get_term($parent_id, 'product_cat');
$grandparent_id = $parent_term->parent;
if ($grandparent_id != 0) {
return $term->name;
}
}
}
}
}
add_shortcode('productname', 'grandchild_category_shortcode');
我尝试仅选择产品的孙项,但这没有任何作用。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我成功让它工作了!这是 [brandname] 短代码的工作代码:
function child_category_shortcode($atts) { global $post; $product_terms = get_the_terms($post->ID, 'product_cat'); if (!empty($product_terms)) { $child_terms = array(); foreach ($product_terms as $term) { if ($term->parent != 0) { $parent = get_term($term->parent, 'product_cat'); if ($parent->parent == 0) { array_push($child_terms, $term->name); } } } return implode(', ', $child_terms); } }