最近,我们的一位用户询问我们如何仅在存在特定自定义字段时显示 WordPress 帖子。在回复完答案后,我们认为最好与其他人分享,这样更大的社区也可以从中受益。
最近,我们的一位用户要求我们仅在存在特定自定义字段时才显示 WordPress 帖子。回答后,我们认为与其他人分享是个好主意,以便更大的社区也能从中受益。
您需要充分了解 WordPress 循环的工作原理,因为我们将在 WordPress 查询中调用这些参数。
您需要对 WordPress 循环的工作原理有一个公正的了解,因为我们将在 WordPress 查询中调用这些参数。
The example code below will only show posts that have a custom field color present no matter what value the color field has. You would need to paste this loop code wherever you want to posts to show. Most likely in a 自定义 WordPress 页面模板.
下面的示例代码将仅显示具有自定义字段颜色的帖子,无论颜色字段的值是多少。 您需要将此循环代码粘贴到要显示的任何位置。 最有可能在自定义 WordPress 页面模板 。
<?php
// The Query to show a specific Custom Field
$the_query = new WP_Query('meta_key=color');
// The Loop
while ( $the_query->have_posts() ) : $the_query->the_post();
the_title();
the_content();
endwhile;
// Reset Post Data
wp_reset_postdata();
?>
现在,如果您想显示具有特定值的自定义字段的帖子,那么您只需更改查询,如下所示:
现在,如果您想显示包含具有特定值的自定义字段的帖子,您只需按如下方式更改查询:
$the_query = new WP_Query( 'meta_value=blue' );
现在,如果您想强调键和值,例如您只想提取具有自定义字段键颜色且值为蓝色的帖子,那么您的查询代码将如下所示:
现在,如果您想强调键和值,例如,您只想提取具有自定义字段键颜色和蓝色值的帖子,那么您的查询代码将如下所示:
$the_query = new WP_Query( array( 'meta_key' => 'color', 'meta_value' => 'blue' ) );
There are a lot more custom parameters that you can use while working on your sites. Just refer to the Codex page for WP_查询参数.
在网站上工作时,可以使用更多自定义参数。 只需参考Codex页面的WP_Query参数可以是 。