简体   繁体   中英

WP_Query Ordering by Specific Value First

I need to add a pre_get_posts action to my WooCommerce store. 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'.

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.

For example : Red TShirt ( AU ), Blue TShirt ( AU ), Black TShirt (UK), Pink 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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