2015-12-31 52 views
2

我試圖創建一個循環,顯示一個標籤與循環所在的頁面標題相匹配的帖子列表。顯示標籤與頁面標題匹配的帖子

例如,我有一個名爲「國家」的自定義帖子類型列表,並且在每個國家/地區都有最近的帖子列表。對於每個國家我都想顯示帶有與該國家/地區相關的標籤的帖子。因此,如果某個帖子包含「UK」標籤,那麼只有這些帖子應顯示在「英國」頁面上。

這裏是我到目前爲止的代碼不工作在所有...

$country_tag = get_the_title(); 

    global $wp_query; 
    $args = array(
    'tag__in' => 'post_tag', //must use tag id for this field 
    'posts_per_page' => -1); //get all posts 

    $posts = get_posts($args); 
    foreach ($posts as $post) : 
    //do stuff 
    if ($posts = $country_tag) { 
    the_title(); 
    } 
    endforeach; 

回答

2

假設你在$country_tag得到了正確的值,假設(根據您的問題)$country_tag是標籤名稱(而不是標籤嵌塊或ID),那麼您必須在您的get_posts中使用Taxonomy Parameters,或者首先獲取標籤的ID或塊。您可以使用get_term_by

此外,在您可以對帖子進行操作之前,您需要致電setup_postdata

我建議首先使用get_term_by,這樣您可以首先檢查標記是否存在,如果不存在則輸出消息。

$country_tag = get_the_title(); 

$tag = get_term_by('name', $country_tag, 'post_tag'); 

if (! $country_tag || ! $tag) { 
    echo '<div class="error">Tag ' . $country_tag . ' could not be found!</div>'; 
} else { 
    // This is not necessary. Remove it... 
    // global $wp_query; 
    $args = array(
     'tag__in'  => (int)$tag->term_id, 
     'posts_per_page' => -1 
    ); 

    $posts = get_posts($args); 
    // be consistent - either use curly braces OR : and endif 
    foreach($posts as $post) { 
     // You can't use `the_title`, etc. until you do this... 
     setup_postdata($post); 
     // This if statement is completely unnecessary, and is incorrect - it's an assignment, not a conditional check 
     // if ($posts = $country_tag) { 
      the_title(); 
     // } 
    } 
} 

上面,我是推薦的get_term_by方法,因爲它允許您首先確認有是一個標記使用該名稱。如果你是100%的信心,總有對應於頁面標題標籤,你可以使用分類參數(如下所示):

$country_tag = get_the_title(); 

$args = array(
    'tax_query' => array(
     array(
      'taxonomy' => 'post_tag', 
      'field' => 'name', 
      'terms' => $country_tag 
     ) 
    ), 
    'posts_per_page' => -1 
); 

$posts = get_posts($args); 
foreach($posts as $post) { 
    setup_postdata($post); 
    the_title(); 
} 
+0

我說「英國」的帖子和頁面標籤我正在將其視爲「聯合王國」的頭銜。然而,使用循環,你很好地放在一起,不幸的是沒有返回。 – Amesey

+0

等待忽略......你提供的第一個循環工作。第二個循環沒有任何回報......我認爲你做到了:) – Amesey

相關問題