Wordpress Basic 循环问题 WP_Query

Wordpress Basic looping issue WP_Query

我正在开发一个 wordpress 主题,并且 运行 在使用 WP_Query 获得自定义 post 类型后我的页面高级自定义字段不可用的以下问题,如下图:

index.php 片段

    //passing in the post id of page with advanced custom fields called 'home'
    $indexPosts = new WP_Query("post_type" => "page", $post_id = $post->ID); 

    while($indexPosts->have_posts()){
       $indexPosts->the_post();

       //do stuff with home pages advanced field data, all fields available and working
       get_field('somecustomfield_from_home_page'); //NON empty

       //get custom post
       $customPost = new WP_Query("post_type" => "mycustompost");

       while($customPost->have_posts()){
           $custom_post->the_post();

           //do stuff with custom post data, all is working

       }
       wp_reset_postdata();        

       //trying to do stuff with home pages acf data, all fields empty
        get_field('somecustomfield_from_home_page'); //empty
    }
    wp_reset_postdata();

我不确定您为什么要使用自定义查询来输出主页 post 数据。这应该在默认查询下可用。我强烈 推荐使用 front-page.php 页面模板作为主页(recommended by the docs)。如果这样做,您可以将所有内容简化为以下内容:

// Default query / Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();

    // do stuff with advanced field data
    // This will use the $post_id from the default query
    get_field('somecustomfield_from_home_page');

    //get custom post
    $customPost = new WP_Query("post_type" => "mycustompost");

    if ( $customPost->have_posts() ) :
        while ( $customPost->have_posts() ) : $custom_post->the_post();
            //do stuff with custom post data, all is working
        endwhile;
        wp_reset_postdata();        
    endif;

    // do stuff with home pages acf data again
    get_field('somecustomfield_from_home_page');

endwhile; endif;