Skip to content

Instantly share code, notes, and snippets.

@hslaszlo
Last active March 12, 2021 02:34
Show Gist options
  • Save hslaszlo/2eee3741039e5a1afcfff396e662bceb to your computer and use it in GitHub Desktop.
Save hslaszlo/2eee3741039e5a1afcfff396e662bceb to your computer and use it in GitHub Desktop.
Query to sort a list by meta key first (if it exists), and show remaining posts without meta key ordered by title.
<?php
$term = get_queried_object();
the_post();
$wp_query = new WP_Query( array(
'post_type' => 'resource',
'tax_query' => array(
array(
'taxonomy' => 'resource_types',
'field' => 'slug',
'terms' => $term->name,
)),
'meta_query' => array(
'relation' => 'OR',
array( //check to see if date has been filled out
'key' => 'publication_date',
'compare' => '=',
'value' => date('Y-m-d')
),
array( //if no date has been added show these posts too
'key' => 'publication_date',
'value' => date('Y-m-d'),
'compare' => 'NOT EXISTS'
)
),
'meta_key' => 'publication_date',
'orderby' => 'meta_value title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => '10',
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment