WP_Query 在 wordpress 中并在结果中包含 ACF

WP_Query in wordpress and include ACF in results

我尝试从 Wordpress 中的自定义 post 类型中获取所有 post,并在结果中包含高级自定义字段 (ACF),以便生成 JSON 包含数据的文件。

$query = new WP_Query(array(
  'post_type' => 'resources',
  'post_status' => 'publish',
  'posts_per_page' => -1,
));

echo "var json=". json_encode($query->get_posts());

使用简单的 WP_Query,ACF 数据不包括在内,我必须迭代结果并一个一个地手动获取所有 ACF。有什么方法可以将它们包含在原始 WP_Query 结果中吗?

在查询中添加ACF数据。 WP_Query 无济于事。

WP_Query 不会 return 来自任何自定义字段的值。要获得这些,您必须遍历帖子并获取字段的值。

参考此文档:https://www.advancedcustomfields.com/resources/query-posts-custom-fields/

您可以使用 get_fields() 一次获取使用 post 注册的所有 acf 字段。查看文档 here.

这就是我的做法。

将你想要的任何内容推送到数组并对其进行编码。

<?php
$array = array();

$args         = array(
    'post_type'      => 'resources',
    'post_status'    => array( 'publish' ),
    'nopaging'       => true,
    'posts_per_page' => '-1',
    'order'          => 'ASC',
    'orderby'        => 'ID',

);
$queryResults = new WP_Query( $args );

if ( $queryResults->have_posts() ) {
    $counter = 0;
    while ( $queryResults->have_posts() ) {
        $queryResults->the_post();
        $array[ $counter ][ 'ID' ]           = get_the_ID();
        $array[ $counter ][ 'name' ]         = get_the_title();
        $array[ $counter ][ 'thumbnailURL' ] = get_the_post_thumbnail_url();
        $array[ $counter ][ 'place' ]        = get_field( 'resource_location' );
        //etc etc etc

        $counter++;
    }

    $jasoned = json_encode( $array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
    echo $jasoned;
} else {
    //nothing found
}
wp_reset_postdata();