获取最新的帖子与特定的自定义字段 - WordPress的

问题描述:

我试图减少我在杂志网站的主页上有多个循环的数量。获取最新的帖子与特定的自定义字段 - 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

是的,您可以在一个循环中获得最新的后期过滤器特色元值。 –

功能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

您可以合并两个查询

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