Support

Account

Home Forums General Issues Query Posts with WP_Query and grab ACF fields

Solved

Query Posts with WP_Query and grab ACF fields

  • I have a category of posts in my admin area – Featured Posts – what I am trying to do is to query the most recent 5 posts from this category (which currently works) and also include the ACF fields associated with those posts.

    $args = array( 
    	'post_type' => 'post', 
    	'cat' => 4, 
    	'orderby' => 'date', 
    	'posts_per_page' => 5,
    );
    $featured_posts = new WP_Query($args);

    The above is my query – I’m wanting to add my two custom fields:

    – featured_post_excerpt
    – featured_post_image

    to the query – I’m not sure the exact terminology on how to ask for assistance with the query – I’ve tried googling but can’t seem to find anything.

  • Are you trying to filter the posts that are returned by these fields or are you trying to somehow have the returned post array include the content of the fields?

    The first is possible.

    The second is not really possible. WP_Query does not return values from custom fields. To get these you must loop through the posts and get the values of the fields.

    
    if ($featured_posts->have_posts()) {
      while($featured_posts->have_posts()) {
        $featured_posts->the_post();
        $value = get_field('my_custom_field');
      }
    }
    
  • great – the second part is what I was asking.

    I’ll go from here – thanks for the quick answer!

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Query Posts with WP_Query and grab ACF fields’ is closed to new replies.