如何在Woocommerce中通过自定义分类法订购产品?

时间:2018-10-15 17:18:20

标签: sorting woocommerce custom-taxonomy

我已经花了很长时间寻找解决问题的方法,但是似乎找不到(或者我不太了解在这里找到的一些帖子)。

问题是,我已经在自己的网站上创建了一个自定义标签,即“ marca”(标签,英文)。我的客户希望按此标签(“ marca”)并按字母顺序对她的所有产品进行排序。但是,默认情况下,Woocommerce会按标题,日期,价格对产品进行排序...您知道,但是如果我要自定义排序,则非常困难。

我已经尝试了该论坛中的一些代码,但不幸的是,它们根本不起作用。可以做到这一点吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

我制作了一个WP_Query示例,为您提供了说明,它返回分类为“ marca”的“ product”类型的帖子,这些帖子按字母顺序设置术语。

$query_args = array(
    'post_type' => 'product', // The post type we want to query, in our case 'product'.
    'orderby' => 'title',     // Return the posts in an alphabetical order.
    'order' => 'ASC',         // Return the posts in an ascending order.
    'posts_per_page' => -1,   // How many post we want to return per page, -1 stands for no limit.
    'tax_query' => array(     // Taxonomy query
        array(
            'taxonomy' => 'marca',  // The taxonomy we want to query, in our case 'marca'.
            'operator' => 'EXISTS'  // Return the post if it has the selected taxonomy with terms set, in our case 'marca'.
        )
    )
);

$query = new WP_Query( $query_args );
if( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        echo the_title();
    }
}


编辑: 这是您可以粘贴在代码段中的代码。它钩住woocommerce_product_query并更改所有存档页面上的查询。

function custom_woocommerce_product_query( $query ){

    $query->set( 'orderby', 'title' ); // Return the posts in an alphabetical order.
    $query->set( 'order', 'ASC' ); // Return the posts in an ascending order.

    $tax_query = array(
        'taxonomy' => 'marca',  // The taxonomy we want to query, in our case 'marca'.
        'operator' => 'EXISTS'  // Return the post if it has the selected taxonomy with terms set, in our case 'marca'.
    );
    $query->set( 'tax_query', $tax_query );
}

add_action( 'woocommerce_product_query', 'custom_woocommerce_product_query', 10, 1 );