我使用 2 個(gè)短代碼 [品牌名稱(chēng)] 和 [產(chǎn)品名稱(chēng)] 在產(chǎn)品單一範(fàn)本上顯示子分類(lèi)術(shù)語(yǔ)和孫分類(lèi)術(shù)語(yǔ)。
範(fàn)例 1:智慧型手機(jī) > Apple > iPhone 14
範(fàn)例2:平板電腦 > Apple > iPad Pro 12.9 吋(第 5 代)
範(fàn)例 1 短程式碼效果很好 範(fàn)例 2 短代碼沒(méi)有,兩個(gè)短代碼都顯示孫分類(lèi)術(shù)語(yǔ)。
程式碼:
/*** 產(chǎn)品單頁(yè)簡(jiǎn)碼的品牌名稱(chēng)*/ 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'); /*** 產(chǎn)品單頁(yè)簡(jiǎn)碼的產(chǎn)品名稱(chēng)*/ 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');
我嘗試只選擇產(chǎn)品的孫項(xiàng),但這沒(méi)有任何作用。
我成功讓它工作了!這是 [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); } }