2016-06-30 14 views
0

私は製品の下に登録したカスタム分類法「w_label」を表示しようとしています。しかし、私は以下のコードでそれを表示しようとしたとき:WooCommerceはアーカイブ内のカスタム分類を表示します

register_taxonomy('w_label', array('product'), 
    array( 
     'hierarchical' => true, 
     'label' => 'Product Labels', 
     'singular_label' => 'Product Label', 
     'rewrite' => true, 
     'supports' => array('excerpt', 'thumbnail') 

    ) 
); 

function w_label_name() { 
    global $post; 
    $terms = get_the_terms($post->ID, 'w_label'); 
    foreach ($terms as $term){ 
     echo '<div class="label">' . $term->name . '</div>'; 
    } 

} 
add_action('woocommerce_before_shop_loop_item_title', 'w_label_name', 2); 

私は得続ける「警告:foreachのために供給無効な引数を()」

ない私が見逃しているものを確認してください。このコードをデフォルトのWooCommerceカテゴリに使用すると動作しますが、ここで登録したカスタム分類には使用できません。

答えて

3

まず$termsを表示するため、$terms = get_the_terms($post->ID, 'w_label');試してみると、問題はこれがあなたの関数ではありませんかどうかを確認してみてください。

function w_label_name() { 
    global $post; 
    $terms = get_the_terms($post->ID, 'w_label'); 
    echo '<div class="label">' . var_dump($terms) . '</div>'; 
} 

その後もget_terms('w_label');代わりget_the_terms($post->ID, 'w_label');のを試してみて、何を見てもvar_dump($terms)それとをエコーが得ている。

何か問題が発生した場合は、$term->nameとなり、方法は$termsになります。これは、製品のループに正しくラベルを示して私のコードです

function w_label_name() { 
    global $post; 
    $terms = get_terms('w_label'); 
    if (! empty($terms) && ! is_wp_error($terms)){ 
     foreach ($terms as $term) { 
      echo '<div class="label">' . $term->name . '</div>'; 
     } 
    } 
} 
add_action('woocommerce_before_shop_loop_item_title', 'w_label_name', 10); 
+0

私はwpobjectエラーが発生します。いくつかのテストの後、私はこのユースケースに対してこのカスタム分類法を作成したので、get_termsメソッドに変更するようになった。 – mark5

1

:その後、(未テストので、いかなる保証なし)このを試みることができる

function w_label_name() { 
    global $post; 
    $taxonomyName = "label_name"; 
    terms = get_terms($taxonomyName, array('hide_empty' => 0)); 
    echo '<div class="label"><ul>'; 
     foreach ($terms as $term) { 
      ?><li><?php echo $term->name; ?></li><?php 
     } 
    echo '</ul></div>'; 
} 
add_action('woocommerce_before_shop_loop_item_title', 'w_label_name', 2); 

も参照してください what is the difference between get_terms and get_the_terms in WordPress ? 用get_termsとget_the_termsメソッド

関連する問題