简体   繁体   中英

Can a single WP_Query get posts from X tag, but if no results, fallback to X category

Is it possible to run a single WP_Query:

$args = array(
    'tag__in' => 5
);
new WP_Query( $args );

but if 0 posts are found, to show from X category?

Is the only way to check for have_posts() and if zero to run a new query with the category? Hopefully not.

Not sure if this is exactly what you'd want to do because there is still another query being run, but you could use get_term_by before you run the query to check and see if there are any posts with that tag. Then modify the $args array depending on what gets returned.

Haven't done any testing, but something like this should work.

$args = array();
$total = get_term_by( 'id', 5, 'post_tag' );

if ( $total->count > 0 ) {
    $args['tag__in'] = 5;
} else {
    $args['cat'] = 1;
} 
new WP_Query( $args );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM