Brett
Brett

Reputation: 20049

Getting custom post type data including ACF with Timber?

I need to get custom post type data for usage with Timber and Twig, it's working fine using the standard WP_Query, such as:

// Get the testimonials custom post type posts
$args = array(
    'post_type' => 'testimonial',
    'post_status' => 'publish',
    'perm' => 'readable',
    'nopaging' => true
);

$context['testimonials'] = new WP_Query( $args );

// Restore the global $post to the current post in the main query
wp_reset_postdata();

However this obviously doesn't get ACF fields.

Was going to do the below as indicated in the Timber docs:

// Get the testimonials custom post type posts
$args = array(
    'post_type' => 'testimonial',
    'post_status' => 'publish',
    'perm' => 'readable',
    'nopaging' => true
);

$context['testimonials'] = Timber::get_posts( $args );

However, it seems that get_posts is getting deprecated in 2.0.

It seems like the best way to do it would be by using Timber's PostQuery, but because of lacking documentation I am unsure if it is more or less an encapsulation of WP_query and I can simply do something like:

// Get the testimonials custom post type posts
$args = array(
    'post_type' => 'testimonial',
    'post_status' => 'publish',
    'perm' => 'readable',
    'nopaging' => true
);

$context['testimonials'] = new PostQuery(array('query' => $args));

Am I on the right track here or what is the correct way?

Upvotes: 0

Views: 1794

Answers (2)

Brett
Brett

Reputation: 20049

Ok, after finding this answer and also digging through the code a bit I found out how to do it I believe:

// Get the testimonials custom post type posts
$args = array(
    'post_type' => 'testimonial',
    'post_status' => 'publish',
    'perm' => 'readable',
    'nopaging' => true
);

$query = new Timber\PostQuery($args);

// Get an array of post objects
$context['posts'] = $query->get_posts();

From what I can tell, all the respective WP_Query args seems to work using this method as well - but if you need pagination to work I would advise reading that other answer I linked to as it contains more information on that.

Upvotes: 2

fxrgc
fxrgc

Reputation: 110

ACF fields have some weird numerical keys in the database. To get the data just use their own function get_fields(); https://www.advancedcustomfields.com/resources/get_fields/

Upvotes: 0

Related Questions