How do you order by 2 meta values in Wordpress? - php

I am using Woocommerce, although my question relates to WP_Query in general. I am creating a custom WP_Query loop for bestselling products and I want to allow users to be able to sort the results by price, from high to low and low to high. The problem is in Woocommerce both _price and total_sales are meta fields and as far as I can tell I can only orderby 1 meta field in Wordpress loops. Is there a way around this?
My full code including some of my attempts is here, the most relevant code segment looks like as follows:
$queryArgs = array(
'post_type' => 'product',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
)
),
'meta_key' => '_price',
'orderby' => array('meta_value_num' => $sortBy['terms'])
);
The actual code is more complicated than this because it's built for a range of filtering and sorting options, but this is the gist of it and bestsellers is the only thing giving me issues because of the two meta_keys. I've read this but it doesn't apply to custom meta fields.
I've tried:
'meta_key' => '_price total_sales'
'meta_key => array('_price', 'total_sales')
'orderby' => array('meta_value_num' => $sortBy['terms'], 'meta_value_num' => 'DESC')
Nothing seems to work. I've also tried hooking onto the various WP_Query filters but the problem is this query is part of a dynamically generated loop so I can't 'hack' or hard-code anything.

Use the meta query with arrays:
'meta_query' => array (
array (
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
),
array (
'key' => '_price',
'value' => "VALUE WHAT YOU WANT, NOT ASC/DESC",
)
),

Related

What is the best approach to checking stock in a Woocommerce meta query

I'm creating a one-way relationship between two products, with the 'linked-to' product outputting the product information of the 'linked-from' product.
I'm able to use a custom field to create the relationship, and use a meta query to generate the results based on this field, but I also need to check that the 'linked-from' product is still either In Stock (if not being stock managed), or has more than 0 as a stock quantity.
This is the approach I have taken so far, which returns no matching results (when indeed there are matches):
$the_query = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'product',
'meta_key' => 'exact_new_version',
'meta_value' => $product->get_id(),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_stock_status',
'value' => array('instock'),
'compare' => 'IN',
),
array(
'key' => '_stock_quantity',
'value' => 0,
'compare' => '>'
)
)
));
The alternative is to check the stock of the returned match(es) in the query loop, but I imagine this to be far less efficient.
I've managed to achieve the desired result by passing in two sets of associative arrays into the meta query with an AND relationship, one of which (checking stock) containing a further two nested assoc. arrays with an OR relationship.
Essentially, the meta value has to match either an 'instock' item (if stock control isn't being used), or an item with '> 0' in stock, if it is:
$the_query = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'product',
'meta_query' =>
array(
'relation' => 'AND',//*
array(
'key' => 'new_version',
'value' => $product->get_ID(),
'compare' => 'LIKE',
),
array(
'relation' => 'OR', //**
array(
'key' => '_stock_status',
'value' => array('instock'),
'compare' => 'IN',
),
array(
'key' => '_stock_quantity',
'value' => 0,
'compare' => '>',
),
),
),
));

Sort wp_query by multiple meta keys (numeric) in specific order

I need to sort a query by a specific order and I failed many times on finding the right solution, but nothing helped – so I'm asking for some hints what I'm doing wrong.
Short story: I have a wp_query showing bikes ordered by the cheapest price. It's working so far. But now I want to show some promotional bikes at first before the order by price starts. So the promotional bikes are showing first and then the "normal" loop.
Promotional bikes are tagged by a ACF field called "promotional_bikes".
This is my wp_query:
$args = array(
'post_type' => 'bikes',
'posts_per_page' => -1,
'facetwp' => true,
'post_status' => 'publish',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_key' => 'baseprice_0_rate', // it's a repeater field in acf
);
meta_key = baseprice_0_rate
meta_value = 100 - 1000 // different values because of the prices
meta_key = promotional_bike
meta_value = 1 // because true or false in acf
This was my last try:
$args = array(
'post_type' => 'bike',
'posts_per_page' => -1,
'facetwp' => true,
'post_status' => 'publish',
'meta_query' => array(
'promo_bike' => array(
'key' => 'promotional_bike',
'compare' => 'EXISTS',
),
'cheapest_bikes' => array(
'key' => 'baseprice_0_rate',
'compare' => 'EXISTS',
),
),
'orderby' => array(
'promotional_bike' => 'ASC',
'cheapest_bikes' => 'meta_value_num',
)
);
but I get 0 results and it doesnt work.
Can anybody give me a hint how to first show the promo bikes and then show the bikes (cheap to high) ?
Many thanks :-)
I came across this while trying to figure out how to orderby multiple numeric meta fields. Finally got it figured out and wanted to post some tips in case anyone else arrives here for the same reason.
Assuming the OP's query had returned results, here's how to sort by multiple numeric meta fields. The key is the type attribute when defining the meta_query clauses.
$args = [
'post_type' => 'bike',
'posts_per_page' => -1,
'facetwp' => true,
'post_status' => 'publish',
'meta_query' => [
'promo_bike' => [
'key' => 'promotional_bike',
'compare' => 'EXISTS',
'type' => 'NUMERIC', // makes orderby sort numerically instead of alphabetically
],
'cheapest_bikes' => [
'key' => 'baseprice_0_rate',
'compare' => 'EXISTS',
'type' => 'NUMERIC',
],
],
'orderby' => [
'promo_bike' => 'DESC', // assuming you want promotional_bike=1 at the top
'cheapest_bikes' => 'ASC',
],
]
Sources:
https://ideone.com/RUoyZs
https://wordpress.stackexchange.com/questions/246355/order-by-multiple-meta-key-and-meta-value
you don't need to code for that. simply you can short your product from Category>Count and then you can drag & drop... for better understanding - you can see my video tutorial.

Wordpress sort by number custom fields gives different results

I have a query which gives me custom post type posts which are sorted by category and a custom fields which has a number that indicates the amount of votes for the post. The problem is, if 2 posts have 3 votes, sometimes when you refresh, it changes their position. Here is the code:
$args = array(
'numberposts' => 10,
'post_type' => 'nominees',
'meta_query' => array(
array(
'key' => 'category',
'value' => get_the_ID(),
'compare' => '=',
)
),
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_key' => 'count_nominees'
);
I tried adding order on the category meta query, but nothing changes, I still sometimes get different results when refreshing, if the posts have same amount of votes. What is the right way to add second order, by ID or something?
Thanks.
As mentioned in the comments, I think this might help, but you might be able to extend it to be a little more specific in the search query for your use case.
$args = array(
'numberposts' => 10,
'post_type' => 'nominees',
'meta_query' => array(
array(
'key' => 'category',
'value' => get_the_ID(),
'compare' => '='
)
),
'meta_key' => 'count_nominees',
'orderby' => array(
'count_nominees' => 'DESC',
'ID' => 'DESC'
)
);
That should get 10 posts in the nominees post type, only if they're part of category xyz, and have post meta of count_nominees and order by count_nominees first in descending order and then by the post ID in descending order.
You can use the WP_Query documentation on the WordPress codex for more information about complex queries using post meta data.

Wordpress AJAX Load More Orderby Meta_VALUE_NUM

Helo,
I have multiple meta_key value pairs inside my custom posts. So to work around this what I did is that I ran a WP_QUERY initially which creates an array of posts ID which I then pass to load more to load those.
The array that I build using WP_Query is in the correct order. However when I use the IDs in post_in parameter it is not displaying them in the given order. I have also tried to give orderby="meta_value_num" parameter but it doesnt work either.
Here is WP_QUERY which is working perfectly
$loop = new WP_Query(
array(
'post_type' => 'properties',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'listing_type',
'value' => array(3,2),
'type' => 'NUMERIC',
),
array(
'key' => 'payment_status',
'value' => 'yes',
),
array(
'key' => 'expired',
'value' => 'no',
- ),
),
'orderby' => 'meta_value_num',
'meta_key' => 'listing_type',
'order' => 'DESC'
));
Here is the shortcode:
[ajax_load_more post_type="properties" post__in="'.implode(',',$featured).'" posts_per_page="10" scroll="false" transition="fade" button_label="'.$l_more.'" button_loading_label="'.$l_more_2.'" container_type="ul" css_classes="items",orderby="meta_value_num" meta_key="listing_type"]
However it doesnt order posts as it should because $featured array has it in required order. Even if I remove order by and meta_key parameter it doesnt work.
Please Help
Ahmar
First, you have an error in your shortcode.
[ajax_load_more post_type="properties" post__in="'.implode(',',$featured).'" posts_per_page="10" scroll="false" transition="fade" button_label="'.$l_more.'" button_loading_label="'.$l_more_2.'" container_type="ul" css_classes="items" orderby="meta_value_num" meta_key="listing_type"]
Second, you should orderby="post__in" to preserve the post__in ordering.
https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

WP_Query with Custom Field Parameter (checkbox)

I'm trying to set up a custom query that returns only posts that do not have a custom meta field checkbox is checked. The checkbox meta field id is position-filled.
Here is the code I have:
$args = array (
'post_type' => 'jobs',
'posts_per_page' => 4,
'post__not_in' => array(get_the_id()),
'meta_query' => array(
array(
'key' => 'position-filled',
'value' => 'on', // also tried passing null and removing 'compare'
'compare' => '!=' // also tried 'NOT LIKE'
)
),
);
$customQuery = new WP_Query($args);
However, this returns no posts (I have made certain there are posts without the checkbox checked.
Any idea what I'm doing wrong?
I've run into similar issues when adding custom fields to existing posts/pages where I needed to search on "unchecked" or "unselected" fields.
It boils down to the fact that the query is actually saying, "Give me posts where the meta key (position-filled) is populated, but not populated with a value of 'on'".
Does it work if you re-save your post with the checkbox being unchecked?
If so, you might also try using the 'compare' value of 'NOT EXISTS'. Although I believe if you use NOT EXISTS and then someone saves an older post without the checkbox being checked, it will exist (with a blank value).
[edit]
I forgot to mention that you can build a query with either situation being true (the NOT EXISTS or it does exist but the value is blank/unchecked).
$args = array(
'post_type' => 'jobs',
'posts_per_page' => 4,
'post__not_in' => array(get_the_id()),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'position-filled',
'value' => 'on',
'compare' => '!='
),
array(
'key' => 'position-filled',
'value' => '',
'compare' => 'NOT EXISTS'
)
)
);
You can chain multiple comparisons together and using the relation property of OR, either one should return true.

Categories