【问题标题】:How to order products by custom taxonomies in Woocommerce?如何在 Woocommerce 中按自定义分类法订购产品?
【发布时间】:2019-03-20 04:16:24
【问题描述】:

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

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

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

谢谢。

【问题讨论】:

  • 你实际使用什么代码来完成排序?
  • 您需要的是分类查询:codex.wordpress.org/Class_Reference/WP_Query
  • @jjj 我尝试了各种代码但没有成功。我想我做错了什么。例如来自这个威胁:stackoverflow.com/questions/39163255/… 或者这个:stackoverflow.com/questions/50937078/… 我正在使用 Code Snippets 插件来引入代码(不是 int functions.php)。
  • @DanielVisser 谢谢,但我迷失了这种信息。我对代码知之甚少,所以我不太了解......对不起。所以,如果有人能告诉我如何做到这一点,我正在寻求帮助:(
  • 我用一个例子发布了我的答案。

标签: sorting woocommerce custom-taxonomy


【解决方案1】:

我为您做了一个 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();
    }
}


编辑: 这是您可以粘贴到代码 sn-p 中的代码。它挂钩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 );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    相关资源
    最近更新 更多