子和孫產品分類術語的自訂短代碼未按預期工作
P粉940538947
P粉940538947 2024-03-20 11:59:26
0
1
620

我使用 2 個短代碼 [品牌名稱] 和 [產品名稱] 在產品單一範本上顯示子分類術語和孫分類術語。

範例 1:智慧型手機 > Apple > iPhone 14

範例2:平板電腦 > Apple > iPad Pro 12.9 吋(第 5 代)

範例 1 短程式碼效果很好 範例 2 短代碼沒有,兩個短代碼都顯示孫分類術語。

程式碼:

/*** 產品單頁簡碼的品牌名稱*/

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');

/*** 產品單頁簡碼的產品名稱*/

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');

我嘗試只選擇產品的孫項,但這沒有任何作用。

P粉940538947
P粉940538947

全部回覆(1)
P粉141455512

我成功讓它工作了!這是 [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);
}
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!