2015-10-13 71 views
2

我需要用slug命令「$ product-> get_categories()」的結果。

模板使用此代碼:

$cat_count = sizeof(get_the_terms($post->ID, 'product_cat')); 

//And after... 

<?php echo $product->get_categories(', ', '<span class="posted_in">' . _n('Category:', 'Categories:', $cat_count, 'woocommerce') . ' ', '</span>'); ?> 

我見過的教程,我可以使用此代碼,但不工作(在functions.php中):

function wptt_cat_order($args){ 

    $args['orderby'] = 'slug'; 
    $args['order'] = 'ASC'; 
    return $args; 

} // wptt_cat_order 
add_filter('woocommerce_product_subcategories_args', 'wptt_cat_order'); 

我的其他問題是(但不是比其他問題如此重要),爲什麼他在「_n()」函數中使用$ cat_count,而不是「get_the_terms($ post-> ID,'product_cat')」?首先只是一個數字O_O。

回答

0

簡單的答案:您不能使用該方法來排序類別。

你將需要編寫自己的循環使用wp_get_post_terms(),它允許你傳遞參數(如orderby)。像下面的東西應該工作(但我沒有測試過):

$args = array(
    'orderby' => 'name', 
); 
$product_cats = wp_get_post_terms($product->id, 'product_cat', $args); 
$cat_count = sizeof($product_cats); 

echo '<span class="posted_in">' . _n('Category:', 'Categories:', $cat_count, 'woocommerce'); 
for ($i = 0; $i < $cat_count; $i++) { 
    echo $product_cats[$i]->name; 
    echo ($i === $cat_count - 1) ? '' : ', '; 
} 
echo '</span>'; 
+0

Thanks!當我去家的時候,我試試這個!只有一個問題:爲什麼你使用for循環來打印類別,而在我的代碼中不是必須的?(只能使用_n()函數) – Phyron

+0

['_n()'函數](https://codex.wordpress。 org/Function_Reference/_n)根據金額('$ cat_count')檢索複數或單一格式。如果計數爲1,則會打印「類別」。如果計數> 1,則會打印「類別」。 'for'循環用於使分隔符'''可以有條件地應用(這比使用'foreach'循環好得多。 – rnevius

+0

好吧,我可以試試你的代碼,給我錯誤行:echo $ product_cats [$ i];錯誤:類stdClass的對象不能轉換爲字符串,如果我銷燬了For,他只打印「categories:」,而不是類:: – Phyron