【问题标题】:Ordering WooCommerce Products by Meta Field按元字段订购 WooCommerce 产品
【发布时间】:2018-07-19 21:48:24
【问题描述】:

我的每个产品都有一个特殊的元字段(时间戳)。我想按此时间戳在所有页面上订购我的产品。

这是我的函数文件中当前的代码。产品不重新订购。

add_action( 'woocommerce_product_query', 'mind_woocommerce_catalog_orderby' );
function mind_woocommerce_catalog_orderby( $query ) {
    if(!is_admin() && $query->is_main_query() ) {
        $query->set( 'meta_key','_start_date' );
        $query->set( 'orderby','meta_value' );
        $query->set( 'order','DESC' );
    }
}

我已经确认每个帖子都有一个“_start_date”元字段。

是否有我应该注意的 woocommerce 设置?

【问题讨论】:

    标签: wordpress woocommerce sql-order-by


    【解决方案1】:

    试一试。

    function custom_add_postmeta_ordering_args( $sort_args ) {
    
        $orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
        switch( $orderby_value ) {
    
            // Name your sortby key whatever you'd like; must correspond to the $sortby in the next function
            case '_start_date':
                $sort_args['orderby']  = 'meta_value';
                // Sort by meta_value because we're using alphabetic sorting
                $sort_args['order']    = 'desc';
                $sort_args['meta_key'] = '_start_date';
                // use the meta key you've set for your custom field, i.e., something like "location" or "_wholesale_price"
                break;
    
        }
    
        return $sort_args;
    }
    add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_add_postmeta_ordering_args' );
    // Add these new sorting arguments to the sortby options on the frontend
    function custom_add_new_postmeta_orderby( $sortby ) {
    
        // Adjust the text as desired
        $sortby['_start_date'] = __( 'Sort by start date', 'woocommerce' );
    
        return $sortby;
    }
    add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_add_new_postmeta_orderby' );
    add_filter( 'woocommerce_catalog_orderby', 'custom_add_new_postmeta_orderby' );
    

    【讨论】:

    • 谢谢!我发现问题实际上是因为我使用 Facet WP 进行过滤而引起的。因此,我选择简单地删除 wooCommerce 排序并添加 Facet WP 排序。就像以前一样,将这一切都集中在一个屋檐下。但是,我确实测试了您的代码,并且效果很好!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多