Skip to content

Instantly share code, notes, and snippets.

@jessedmatlock
Forked from hslaszlo/wp-query.php
Created March 12, 2021 02:34
Show Gist options
  • Save jessedmatlock/ea505ad0462ee268af861b528f7a2931 to your computer and use it in GitHub Desktop.
Save jessedmatlock/ea505ad0462ee268af861b528f7a2931 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