I'm running a WP_Query in my functions.php, so I can easily access some ACF-fields in my code without having to run that query on every page.
However, the loop changes the post ID to the CPT I'm calling with the WP_Query. This is of course known behavior, so normally I'd just add a wp_reset_postdata()
to my query to continue with the page's or post's original ID.
However, no matter where I reset the postdata in my query, it doesn't get reset. A temporary, not so pretty, solution I have found is adding wp_reset_postdata();
after I call the function in my page-file. This fixes it, but isn't very pretty and partially beats the purpose of using the function.
Here's my function:
function get_root_project_value( $meta_key ) {
$args = array(
'post_type' => 'slug',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'project_is_root_project',
'value' => '1',
),
)
);
$project = new WP_Query( $args );
if ( $project->have_posts() ) {
while ( $project->have_posts() ) { $project->the_post();
if($meta_key) {
$meta_value = get_field($meta_key, get_the_id());
if($meta_value) {
return $meta_value;
} else {
return false;
}
}
}
wp_reset_postdata();
} else {
return false;
}
}
And this is how I use it in my code:
$longitude = get_root_project_value('project_longitude');
This will set my current page's ID to the root_project ID, so to reset that (since the wp_reset_postdata()
in the function doesn't do that), I add wp_reset_postdata();
just after I set $longitude
.
Is there a way to reset the postdata in the function, instead on every single page I use the function?
return
the function ends, so nothing after that will run.wp_reset_postdata()
to just beforereturn $meta_value
?