繁体   English   中英

更改特定 Woocommerce 产品类别存档页面的默认排序

[英]Change default sorting for specific Woocommerce product category archive pages

我需要将我网站上特定产品类别的默认产品分类选项更改为“新品”。 我知道您可以转到 WooCommerce > 设置 > 产品 > 显示来全局更改默认排序选项,但这不是我需要做的。 我需要类似的东西:

function change_default_sorting_option(){

if(is_product_category('3555')){

//change default sorting option to newness

}

}
add_action('', 'change_default_sorting_option');

我在排序功能方面做得不多,所以我不确定从哪里开始。 我知道该函数应该放在我的子主题的functions.php 中。

这是正确的钩子和获取特定产品类别存档页面的方法,默认排序为“Newness”:

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_catalog_ordering_args', 20, 1 );
function custom_catalog_ordering_args( $args ) {
    $product_category = 't-shirts'; // <== HERE define your product category

    // Only for defined product category archive page
    if( ! is_product_category($product_category) ) return $args;

    // Set default ordering to 'date ID', so "Newness"
    $args['orderby'] = 'date ID';

    if( $args['orderby'] == 'date ID' )
        $args['order'] = 'DESC'; // Set order by DESC

    return $args;
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中 测试和工作。

这里更好且有效的解决方案

add_filter('woocommerce_get_catalog_ordering_args', 'woocommerce_catalog_orderby');
function woocommerce_catalog_orderby( $args ) {
    if( is_product_category( 'shirts' ) ) {  // <- define category slug- returns true or false
        $args['orderby']  = 'meta_value_num';
        $args['order']    = 'ASC'; // <- order ASC or DESC
        $args['meta_key'] = '_price'; // <- _price is meta_value_num's key - required
    }
    return $args;
}

另请阅读有关 WP_Query order & orderby 的信息: https : //developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters

假设您在自定义页面模板中工作,这应该相对容易。 不完全确定您的方法是否适用于使用 is_page() 来强制更改产品的排序,但是...您可以使用全局WP_Query创建自定义查询,根据需要对产品进行排序。 下面是一个例子:

<?php  
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => -1, //or... set your post per page and utilize pagination if required.
        'orderby'        => 'title',
        'order'          => 'ASC',
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;

        //this is where you can output your products
        //which will be ordered according to the set arguments above.

    endwhile;

    wp_reset_query();
?>

编辑

如果您正在为特定类别寻找这种功能,我只需在您的系统中创建一个新页面并使用 WooCommerce 产品短代码。 您不需要在您的functions.php 中添加任何内容或以这种方式挂钩任何内容。 以下短代码是一个示例,您可以使用它...例如,按标题在特定类别页面上订购您的产品。

[products category="yourcategory" orderby="title" ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM