子和孙产品分类术语的自定义短代码未按预期工作
P粉940538947
P粉940538947 2024-03-20 11:59:26
0
1
618

我使用 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');

我尝试仅选择产品的孙项,但这没有任何作用。

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学习者快速成长!