2017-04-11 73 views
1

基本上想顯示term = arts的第一篇文章,如果不存在,則顯示term = guides的文章。條件查詢基於術語的WP_query

這些是我的兩個參數,我一直試圖使用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嗎? 在此先感謝!

回答

1

你接近 - >但是你應該改爲嘗試

<?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 
    }  
} 

應該足以讓你開始:)