Skip to content

Instantly share code, notes, and snippets.

@profstein
Created May 15, 2014 02:26
Show Gist options
  • Save profstein/4c2d289b183a53011cc0 to your computer and use it in GitHub Desktop.
Save profstein/4c2d289b183a53011cc0 to your computer and use it in GitHub Desktop.
WordPress Conditional Custom Query

Conditional Query

This shows an example of doing a second query if the first custom query doesn't return any results.

The first query is for a category with the slug of featured. It checks to see if this has posts and if it doesn't it does a second query for the latest posts. If the second query doesn't have results it just shows the content-none template part. You could change the arguments to make it any other kind of query you want.

Not shown are three template parts: content-featured.php, content-latest.php and content-none.php that show the various contents depending on what query returned results. content-featuerd and content-latest would have whatever HTML and Template Tags you need to show the content in The Loop while content-none could be a message with straight HTML if you like or you can add in things like a search bar or Template Tags that work outside of The Loop.

Note

What is shown is not a full file. It would be included in a full file with get_header(), get_footer() etc like index.php or home.php.

<?php
$args = array('category_name' => 'featured');
$featured = new WP_Query($args);
if ($featured->have_posts()) :
//there were posts
while ($featured->have_posts()) : $featured->the_post();
get_template_part('content', 'featured');
endwhile;
else :
//this means featured didn't have any posts so do another query
$args = array('orderby' => 'date', 'order' => 'DESC')
$latest = new WP_Query($args);
if ($latest->have_posts()) :
//there were posts
while ($latest->have_posts()) : $latest->the_post();
get_template_part('content', 'latest');
endwhile;
else :
//this means latest didn't have any posts so show something, In this case content-none.php
get_template_part('content', 'none');
endif;
endif;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment