【问题标题】:Woocommerce change order of $product->get_categories$product->get_categories 的 Woocommerce 更改订单
【发布时间】:2015-10-13 15:08:14
【问题描述】:

我需要使用 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' )”? first 只是一个数字 O_O。

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    简单的答案:您不能使用该方法对类别进行排序。

    您将需要使用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>';
    

    【讨论】:

    • 谢谢!当我回家时,我试试这个!只有一个问题:为什么你使用 for 循环来打印类别而在我的代码中没有必要?(只取消 _n() 函数)
    • _n() function 根据金额 ($cat_count) 检索复数或单数形式。如果计数为 1,则将打印 Category。如果计数 > 1,则将打印 Categories。使用for 循环以便有条件地应用分隔符, (这比使用foreach 循环效果更好。
    • 好的,我可以试试你的代码,给我一行错误:echo $product_cats[$i];错误:stdClass 类的对象无法转换为字符串。如果我销毁 For,他只打印“类别:”,而不是类别。 :(
    • 我已将该行上的代码编辑为$product_cats[$i]-&gt;name;。请尝试一下,如果它仍然抛出错误,请告诉我。
    • 是的,这工作!只需将 for 循环中“i var”的 de 值更改为 0,因为不会忽略第一只猫;)谢谢!!
    猜你喜欢
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2021-04-08
    • 2018-01-01
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多