[英]Get the most recent post with a specific custom field - Wordpress
Im trying to reduce the amount of multiple loops I have on the homepage of a magazine website. 我正在尝试减少杂志网站首页上的多个循环。
I want to display a post with a specific custom field differently, however I only want the first post (most recent) with that custom field. 我想以不同的方式显示具有特定自定义字段的帖子,但是我只希望具有该自定义字段的第一篇帖子(最新的)。 I can achieve this by creating another loop but I would like it to be included in the loop below.
我可以通过创建另一个循环来实现此目的,但我希望将其包含在下面的循环中。
For example here is my query but I need a further condition for if (get_post_meta($post->ID, 'featured', true)):
so it includes only the most recent post that meets this condition 例如,这是我的查询,但是我需要
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();
The function get_post_meta() returns a value not a boolean, so you have to check if the custom field exist so try with the empty() function 函数get_post_meta()返回的值不是布尔值,因此您必须检查自定义字段是否存在,因此请尝试使用empty()函数
$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();
you can merge two query 您可以合并两个查询
<?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;
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.