2014-03-31 37 views
1

我試圖減少我在雜誌網站的主頁上有多個循環的數量。獲取最新的帖子與特定的自定義字段 - WordPress的

我想用特定的自定義字段以不同方式顯示帖子,但是我只想使用該自定義字段的第一個帖子(最新)。我可以通過創建另一個循環來實現這一點,但我希望它被包含在下面的循環中。

例如,這裏是我的查詢,但我需要進一步的條件if (get_post_meta($post->ID, 'featured', true)):所以它僅包括滿足這個條件

$fourth_query = new WP_Query($args4); 
while($fourth_query->have_posts()) : $fourth_query->the_post(); 
if (get_post_meta($post->ID, 'featured', true)): 
    get_template_part('content-opinion', get_post_format()); 
else : 
    get_template_part('content', get_post_format()); 
endif; 
endwhile; 
wp_reset_postdata(); 
+0

在meta key和value中使用參數來排序你的帖子:https://codex.wordpress.org/Template_Tags/get_posts –

+0

我想我只需要使用另一個循環。有很多這個自定義字段的帖子,我需要最近的一個,我希望我可以在一個循環中做到這一點。 – stemie

+1

是的,您可以在一個循環中獲得最新的後期過濾器特色元值。 –

回答

1

功能get_post_meta()返回一個值不是一個布爾最近的職位,所以你必須檢查,如果自定義字段存在,因此與空()函數嘗試

$fourth_query = new WP_Query($args4); 
while($fourth_query->have_posts()) : $fourth_query->the_post(); 
if (!empty(get_post_meta($post->ID, 'featured', true))): 
    get_template_part('content-opinion', get_post_format()); 
else : 
    get_template_part('content', get_post_format()); 
endif; 
endwhile; 
wp_reset_postdata(); 
+0

我正在尋找具有特定自定義字段的最新帖子,這個自定義字段中有很多帖子。 – stemie

+0

哦對不起。在$ args4中設置showpost => 1 :) – AndrePliz

+0

感謝您的幫助,但是它只會返回一個帖子,在循環中有其他帖子不包含我想要顯示的自定義字段。看來我必須使用兩個循環來實現這一點。 – stemie

1

您可以合併兩個查詢

<?php 
    $generalQuery    = new WP_Query($args); // there is your main query 
    $queryWithCustomField  = new WP_Query($args); // there is your query with custom post and posts_per_page = 1 
    $queryWithCustomField->posts = $queryWithCustomField->posts + $generalQuery->posts; // merge it now 

    if ($queryWithCustomField->have_posts()) : while ($queryWithCustomField->have_posts()) : $queryWithCustomField->the_post(); 
     echo "your first post is "; 
    endwhile; 
    else: 
     echo "No post Found"; 
    endif; 
?> 
相關問題