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

标签 sorting woocommerce custom-taxonomy

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

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

我已经尝试了这个论坛的一些代码,但遗憾的是它们根本不起作用。有可能做到这一点吗?

谢谢。

最佳答案

我做了一个带有解释的 WP_Query 示例,它返回类型为“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();
    }
}


编辑: 这是您可以粘贴到代码片段中的代码。它 Hook 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 );

关于sorting - 如何在 Woocommerce 中按自定义分类法订购产品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52821760/

相关文章:

php - 获取 Woocommerce 单一产品页面中的产品类别名称和描述

php - 在 WooCommerce 产品搜索中启用自定义分类法

php - 自定义分类法未在 Post Gutenberg 编辑器中显示

java - Java 中的 map 排序不起作用

c - 对具有大量元素的数组进行排序时发出 SIGSEGV 信号

woocommerce - 在价格前添加文字

php - WooCommerce 订阅 : Don't have the SUSPEND button

Javascript 在 Woocommerce 结帐事件上执行函数

javascript - 在 javascript/node.js 中迭代对象数组的有效方法

algorithm - NlogN 中最长的递增子序列长度。[了解算法]