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_dump
ing $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.
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');
When using a custom query, in order to access the
$post
information, you need to referencepost
as a class variable the custom WP_Query.Since you constructed the query as:
$hw_selectbox_query = new WP_Query($hw_selectbox_args);
Then you would access the
post
variable of$hw_selectbox_query
, like so:This will give you the information you need / want to build your
$field
array.