简体   繁体   中英

Cannot get ACF from custom post type post

I have a custom post type called "members", which has an ACF field connected. I try to get the content of that field. But when I try, I only get the regular post object. Not the ACF fields connected.

Here is what i am trying, but only getting the post object.

`

$featuredmembers = get_field('featured_member');
global $post;

//$featuredmembers has a field named "featured". That's the field I want.


$posts = get_posts([
  'post_type' => 'members',
  'post_status' => 'publish',
  'posts_per_page' => -1,
  'order' => 'ASC',
  'orderby' => 'title'
]);


foreach ($featuredmembers as $post) {
  print_r($post['featured']->ID);
  echo get_field('featured');
}

`

Try passing the post id in the get_field / the_field call within the foreach loop:

foreach ($featuredmembers as $post) {
    // the_field('featured', $post->ID);
    echo get_field('featured', $post->ID);
}

If it's a repeater field you can use:

foreach ($featuredmembers as $post) {
    the_repeater_field('featured', $post->ID);
}

I think this might be down the foreach loops using a variable of $post . This will override the main $post variable of the page, and any get_field function calls after the foreach loop will be looking at the wrong post.

Try renaming those variables to something other than $post

Have you tried using WP_Query to get access to the post_id?

$args = array(
'post_type'   => 'members',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'title'
);

$query = new WP_Query( $args );

if( $query->have_posts() ) :
  while( $query->have_posts() ) :
    $current_post->the_post();
    $post_id = get_the_ID();
    $featured = esc_html(get_post_meta($post_id, 'featured_member', true));
endwhile;

wp_reset_postdata();

else :
    esc_html_e( 'no members found', 'text-domain' );
endif;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM