简体   繁体   English

WP_Query按特定值先排序

[英]WP_Query Ordering by Specific Value First

I need to add a pre_get_posts action to my WooCommerce store. 我需要在我的WooCommerce商店中添加一个pre_get_posts操作。 The scenario is : 该方案是:

  1. The system will detect the visitor's location. 系统将检测访客的位置。
  2. The products needs to be sorted by their location. 产品需要按其位置分类。

For example : When I search "shirt" and I am from Australia, the first products that will appears needs to be "shirt" and the location = 'AU'. 例如:当我搜索“衬衫”并且我来自澳大利亚时,首先出现的产品应该是“衬衫”,并且位置=“ AU”。

Here is my current code : 这是我当前的代码:

add_action('pre_get_posts', 'my_geo_sort_category_page');
function my_geo_sort_category_page($query) {
    if ( is_product_category() ) {
        if(is_user_logged_in()){
            $current_user = get_current_user_id();
            $visitor_country = get_user_meta($current_user, 'billing_country', true);
        } else {
            $ip = WC_Geolocation::get_ip_address();
            $geolocate = WC_Geolocation::geolocate_ip($ip);
            $visitor_country = $geolocate['country'];   
        }

        $query->set('meta_key', '_ships_from');
        $query->set('orderby', 'meta_value');
        $query->set('order','ASC');

    }
}

I'm not sure where to put 'AU' so that it will appears first then followed by the other products. 我不确定将“ AU”放在哪里,以便先出现然后再出现其他产品。

For example : Red TShirt ( AU ), Blue TShirt ( AU ), Black TShirt (UK), Pink TShirt (CA). 例如:红色TShirt( AU ),蓝色TShirt( AU ),黑色TShirt(UK),粉红色TShirt(CA)。

Not sure if this will work, but try something like: 不知道这是否行得通,但是尝试如下操作:

$meta_query = array(
'relation' => 'OR',
array(
    'key' => '_ships_from',
    'compare' => '=',
    'value' => $visitor_country,
),
array(
    'key' => '_ships_from',
    'compare' => '!=',
    'value' => $visitor_country,
)
);

$query->set( 'meta_query', $meta_query );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'DESC' );

If this doesn't work, try playing around with the values and comparison operators as I think this will be quite close. 如果这不起作用,请尝试使用值和比较运算符,因为我认为这将非常接近。

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

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