获取自定义的帖子类型数据,包括ACF与Timber



我需要获得用于Timber和Twig的自定义帖子类型数据,使用标准WP_Query可以很好地工作,例如:

// Get the testimonials custom post type posts
$args = array(
'post_type' => 'testimonial',
'post_status' => 'publish',
'perm' => 'readable',
'nopaging' => true
);
$context['testimonials'] = new WP_Query( $args );
// Restore the global $post to the current post in the main query
wp_reset_postdata();

然而,这显然没有得到ACF字段。

按照木材文件中的指示,我们将执行以下操作:

// Get the testimonials custom post type posts
$args = array(
'post_type' => 'testimonial',
'post_status' => 'publish',
'perm' => 'readable',
'nopaging' => true
);
$context['testimonials'] = Timber::get_posts( $args );

然而,get_posts在2.0中似乎越来越不受欢迎。

似乎最好的方法是使用Timber的PostQuery,但由于缺乏文档,我不确定它是否或多或少是WP_query的封装,我可以简单地做一些事情,比如:

// Get the testimonials custom post type posts
$args = array(
'post_type' => 'testimonial',
'post_status' => 'publish',
'perm' => 'readable',
'nopaging' => true
);
$context['testimonials'] = new PostQuery(array('query' => $args));

我在这里走的是正确的路还是正确的路?

好的,在找到这个答案并深入研究代码之后,我发现了如何做到这一点,我相信:

// Get the testimonials custom post type posts
$args = array(
'post_type' => 'testimonial',
'post_status' => 'publish',
'perm' => 'readable',
'nopaging' => true
);
$query = new TimberPostQuery($args);
// Get an array of post objects
$context['posts'] = $query->get_posts();

据我所知,所有相应的WP_Queryargs似乎也可以使用这种方法,但如果您需要分页才能工作,我建议您阅读我链接到的另一个答案,因为它包含更多信息。

ACF字段在数据库中有一些奇怪的数字键。要获取数据,只需使用它们自己的函数get_fields((;https://www.advancedcustomfields.com/resources/get_fields/

最新更新