
So I’m trying to populate an Advanced Custom Fields selectbox with a nice complicated array based off some post data. I’ve been trying to do this by doing a custom query and loop through the returned posts.
Unfortunately, the loop seems to return diddly squat. On my test install, it should be returning 10 posts. However, the var_dump in the below statement will return NULL 10 times. Setting get_post($post) inside the loop will return the first result for every instance.
Weirdly, var_dumping $hw_selectbox_query will return a seemingly correct object, so it’s definitely an issue with the actual loop itself not defining the $post object. I could run a foreach loop through the returned query, but that doesn’t feel like the right way to do it.
FWIW, the function runs perfectly when placed on a blank front-end page, so I know it’s syntactically correct.
function populate_selectbox_field( $field ){
$field['choices'] = array();
$hw_selectbox_args = array(
post_type => 'custom_post_type',
orderby => 'title',
order => 'ASC',
posts_per_page => -1
);
$hw_selectbox_query = new WP_Query($hw_selectbox_args);
if ( $hw_selectbox_query->have_posts() ) : while ( $hw_selectbox_query->have_posts() ) : $hw_selectbox_query->the_post();
var_dump($post);
$field['choices'][$post->ID] = $post->post_title
// Do more complicated stuff in real life
endwhile; endif;
return $field;
}
add_filter('acf/load_field/name=destination_node', 'populate_destination_node_field');
Apologies, I was an idiot. You need to access $post as a method of the query. So I should’ve been doing $hw_selectbox_query->post->post_title
.