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

How to order products by custom taxonomies in Woocommerce?

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

问题是我在我的网站上创建了一个自定义标签,即 "marca"(标签,英文)。我的客户想按此标签 ("marca") 和字母顺序对她的所有产品进行排序。但是 Woocommerce 默认情况下按标题、日期、价格对产品进行排序……你知道,但是如果我想自定义排序就非常困难了。

我试过这个论坛的一些代码,但不幸的是它们根本不起作用。有可能做到这一点吗?

谢谢。

我做了一个 WP_Query 示例并为您解释,它 returns 类型为 'product' 的帖子具有分类法 'marca',术语按字母顺序设置。

$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 );