2014-10-02 4 views
6

Woocommerce에서 제품의 상위 카테고리를 워드 프레스 'body 태그로 추가하려고합니다.WP '본문'클래스에 Woocommerce 상위 카테고리 추가

하위 카테고리에 속할 때마다 상위 카테고리는 더 이상 body 클래스 내에 없습니다.

상위 카테고리를 찾고 body 태그 내에 추가하려면 다음과 같이 편집 할 수 있습니까?

"product_parent_cat"과 같은 용어일까요? 이 시도하고 자신의 API하지만 성공 ..

function woo_custom_taxonomy_in_body_class($classes){ 
    $custom_terms = get_the_terms(0, 'product_cat'); 
    if ($custom_terms) { 
     foreach ($custom_terms as $custom_term) { 
     $classes[] = 'product_cat_' . $custom_term->slug; 
     } 
    } 
    return $classes; 
} 

add_filter('body_class', 'woo_custom_taxonomy_in_body_class'); 

답변

7

당신은 (안된)이 수정을 시도 할 수 있습니다 검색 :

function woo_custom_taxonomy_in_body_class($classes){ 
    $custom_terms = get_the_terms(0, 'product_cat'); 
    if ($custom_terms) { 
     foreach ($custom_terms as $custom_term) { 

     // Check if the parent category exists: 
     if($custom_term->parent > 0) { 
      // Get the parent product category: 
      $parent = get_term($custom_term->parent, 'product_cat'); 
      // Append the parent class: 
      if (! is_wp_error($parent)) 
       $classes[] = 'product_parent_cat_' . $parent->slug; 
     } 

     $classes[] = 'product_cat_' . $custom_term->slug; 
     } 
    } 
    return $classes; 
} 

add_filter('body_class', 'woo_custom_taxonomy_in_body_class'); 

몸 클래스에 상위 제품 카테고리 슬러그를 추가 할 수 있습니다.

여기서 우리는 get_term() 함수에 의해 반환 된 용어 개체의 parent 속성을 사용합니다.

+0

감사합니다. 그것을 못 박는. – blkedy

+0

@ user1420650 듣기가 좋았습니다. – birgire

+0

2017 년 소식. Woocommerce 3.0 이상 및 Wordpress 4.8에서 여전히 작동 중 –

관련 문제