首頁  >  問答  >  主體

子和孫產品分類術語的自訂短代碼未按預期工作

我使用 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粉940538947P粉940538947187 天前609

全部回覆(1)我來回復

  • P粉141455512

    P粉1414555122024-03-21 09:49:17

    我成功讓它工作了!這是 [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);
    }
    }

    回覆
    0
  • 取消回覆