I would like to show posts in a custom post type with the category ‘pin-post-to-homepage’, then if that doesn’t exist then display posts from a different post type.
Below are the arguments. Feel like I am very close, as the first query works when a post has the category, though the second loop isn’t working at the moment. Are the args added to the else correctly?
Here is my code:
<?php $first_args = array( 'post_type' => 'timeline', 'posts_per_page' => 1, 'tax_query' => array( array ( 'taxonomy' => 'pin', 'field' => 'slug', 'terms' => 'pin-post-to-homepage', ) ), ); $second_args = array( 'post_type' => 'days', 'posts_per_page' => 1, 'orderby' => 'rand' ); $first_query = new WP_Query($first_args); if ($first_query->have_posts()) { while ( $first_query->have_posts() ) { $first_query->the_post(); ?> <?php get_template_part('partials/andSoOnTimeline'); ?> <?php } } else { $second_query = new WP_Query($second_args); if ($second_query->have_posts() ){ ?> <?php get_template_part('partials/days'); ?> <?php } } ?>
Advertisement
Answer
Try something like this
$first_query = new WP_Query($first_args); $has_results = false; if ($first_query->have_posts()) { $has_results = true; while ( $first_query->have_posts() ) { $first_query->the_post(); get_template_part('partials/andSoOnTimeline'); } } wp_reset_postdata(); if ($has_results === false) { $second_query = new WP_Query($second_args); if ($second_query->have_posts() ){ //Update line below since first post $second_query->the_post(); //... } } wp_reset_postdata();