Support

Account

Home Forums General Issues populate ACF fields on simple custom endpoint

Helping

populate ACF fields on simple custom endpoint

  • Trying to return an array of posts with acf fields populated. My query gives me the desired data of posts although no population of acf Fields. Any help here is greatly appreciated

    function my_events_current_func ( $request_data ) {
      $date_now = date('Y-m-d');
      $posts = new WP_Query(array(
        'posts_per_page' => -1,
        'post_type' => 'event',
        'meta_query' => array (
          array(
            'key' => 'event_date',
            'compare' => '>=',
            'value' => $date_now,
            'type' => 'DATE'
    
          )
        ),
        'order' => 'ASC',
        'orderby' => 'event_date',
        'meta_key' => 'event_date',
        'meta_type' => 'DATE',
      ));
      return $posts->posts;
    }
    add_action( 'rest_api_init', function () {
      register_rest_route( 'thehub/v1', '/current/events', array(
        'methods' => 'GET',
        'callback' => 'my_events_current_func'
      ));
    });
  • Custom fields are stored as meta data in a separate table which are separate to post data and that’s why you don’t get it with wp_query.

    By default, WP_Query returns the standard WP_Post objects for the posts being queried. I believe with some clever rewrite and use of the filters given in WP_Query you can add objects to the returned WP_Post objects array.

    In my opinion, it will hurt performance more as you will need to join results in your query as custom fields are not saved in the wp_posts table, but in the wp_postmeta table.

    You can loop through the posts and attach the required meta data yourself. with $posts->posts; in your example

    Retrieving post meta is really fast and it does not require any extra instance of WP_Query. You can simply call the custom field with get_post_meta(). WordPress was very thoughtful when the custom fields was introduced. They added a cache to cache them, so whether you are querying 1 or 100 custom fields, you are hitting the database once, superfast.

    In my opinion, the extra database call and the actual time spent is worth it and faster than rewriting WP_Query in such a way to include custom fields in the standard post object returned by $posts.

    HTH

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

You must be logged in to reply to this topic.