基于术语的条件查询 WP_query

Conditional queries WP_query based on term

基本上想显示带有 term = arts 的第一个帖子,如果不存在则显示带有 term = guides 的帖子。

这是我的两个论点,我一直在尝试使用 has_term 外部循环但没有用。

<?php

if ( has_term( 'arts', 'postkicker' )){

$args=array(
    'post_type' => 'post',
    'taxonomy'  => 'postkicker',
    'term'      => 'arts',
    'orderby'   => 'date',
    'order'     => 'DESC'
);

} else {

$args=array(
    'post_type' => 'post',
    'taxonomy'  => 'postkicker',
    'term'      => 'guides',
    'orderby'    => 'date',
    'order'      => 'DESC'
);

} 

$my_query = new WP_Query($args);

if ( $my_query->have_posts() ) :
    while ( $my_query->have_posts() ) : $my_query->the_post();
    the_title( sprintf( "<h1><a href='%s' rel='bookmark'>", esc_url( get_permalink() ) ), "</a></h1>" ); 

    endwhile;wp_reset_postdata();endif; 
?>

有什么建议吗?我需要在循环中移动 has_term 吗? 提前致谢!

你很接近 -> 但你应该尝试

<?php

$first_args=array(
    'post_type' => 'post',
    'taxonomy'  => 'postkicker',
    'term'      => 'arts',
    'orderby'   => 'date',
    'order'     => 'DESC'
);


$second_args=array(
    'post_type' => 'post',
    'taxonomy'  => 'postkicker',
    'term'      => 'guides',
    'orderby'    => 'date',
    'order'      => 'DESC'
);

$first_query = new WP_Query($first_args);

if ($first_query->have_posts() ) {
     // Do your HTML
 }
 else {
 $second_query = new WP_Query($second_args);
 if ($second_query->have_posts() ){
    // Do your HTML
    }     
 }

这应该足以让您入门:)