查询WordPress自定义字段的正确方法是什么


What is the proper way to query a Wordpress custom field

我有这个工作查询,它成功地在我的页面模板文件中获取自定义字段数据:

<?php $featuredpost_cat = get_field('featured_category_id'); ?>

如果我将其回显到页面中,我会得到自定义字段的值"23",所以我知道这是有效的,我想做的是获取该值并将其用作查询参数。

在我的页面下方,我有这个:

<?php query_posts( $featuredpost_cat . '&posts_per_page=1'); if (have_posts()) : while (have_posts()) : the_post(); ?>

所做的只是忽略我的变量并返回网站上的最新帖子。

我希望这已经足够清楚了。

== 编辑 ===

如果我不清楚,我想从页面中获取一个自定义字段,该字段是类别ID,然后在页面模板的查询中使用它。

因此,我将字段设置为类别 ID:23,然后在我的 query_posts 函数中调用它,以便我只返回该类别的帖子。

也许整页代码会有所帮助:模板代码

怎么样

<?php query_posts( 'cat='.$featuredpost_cat . '&posts_per_page=1'); if (have_posts()) : while (have_posts()) : the_post(); ?>

我假设 $featuredpost_cat 是一个类别 ID

抱歉,我不明白您的第二个代码示例。您是否正在尝试使用三元运算符来实现此目的?

query_posts('cat='.$featuredpost_cat . '&posts_per_page=1');
if (have_posts()){
  while (have_posts()){
    the_post();
  }
}

query_posts()the_post()做什么?如果query_post()获取帖子,have_post()检查帖子的存在并the_post()页面上回显它们,上面的代码应该可以工作。如果不是这种情况,请告诉函数的作用。


编辑。删除了问号。