I have a setup with WordPress (6.7.2) / ACF (6.3.12) and am trying to order posts, first by the custom field being true and then by date. The custom field is a True/False named pinned
.
The problem I'm coming against is that in the documentation they suggest meta_key
/ meta_value
- but this is acting as a filter and removing posts that don't have the ACF field. If it makes any difference, the posts existed prior to the addition of the ACF field. I've also read the documentation on WordPress around the WP_Query but can't work out my issue.
I've tried various iterations of WP_Query to get this to work, but it either seems to just pull back things in a random order or just ignore the custom field.
Here's my latest WP_Query, trying to get around the filtering by a meta_query
that checks to see if the field is true/1, exists and is false/0 or just doesn't exist at all. Any suggestions would be very welcomed!
$args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'pinned', // ACF field named "pinned"
'compare' => 'EXISTS',
'value' => '1',
'operator' => '='
),
array(
'key' => 'pinned',
'compare' => 'EXISTS',
'value' => '0',
'operator' => '='
),
array(
'key' => 'pinned',
'compare' => 'NOT EXISTS'
)
),
'orderby' => array(
'pinned' => 'DESC',
'post_date' => 'DESC'
)
);
$results = new WP_Query($args);
Thank you very much to both wouch and disinfor for the super useful comments - performing two queries and merging was exactly what I needed to do. Following the link to the WP Stack Exchange, here's the code that does what I need:
// Go get the pinned articles
$pinnedArgs = array(
'post_type' => 'post',
'posts_per_page' => 5,
'meta_query' => array(
array(
'key' => 'pinned',
'value' => '1'
)
)
);
$pinnedResults = new WP_Query($pinnedArgs);
// Grab all the IDs to add to the args, otherwise we may duplicates
$foundIds = wp_list_pluck( $pinnedResults->posts, 'ID' );
$otherArgs = array(
'post_type' => 'post',
'posts_per_page' => 5,
'post__not_in' => $foundIds
);
$otherResults = new WP_Query($otherArgs);
// Merge the two together and return this list
$mergedQuery = new WP_Query();
$mergedQuery->posts = array_merge( $pinnedResults->posts, $otherResults->posts );
$mergedQuery->post_count = $pinnedResults->post_count + $otherResults->post_count;
return $mergedQuery;