Home › Forums › General Issues › Post Object Field doesn't work within a Function
Hi,
iam trying to use a Post Object field within a function but i have no luck so far. Is it even possible and if yes how to do it?
Heres my example code:
If i call the function it outputs the Title of the actual site but not the post object. If i use the code outside of the function everything works fine.
Thanks a lot in advance for any help!
Michael
function example($field, $options) {
$post_object = get_field($field, $options);
if($post_object) {
# get post data
$post = $post_object;
setup_postdata($post);
?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php
# reset postdata
wp_reset_postdata();
}
}
Call of the function:
example('my_post_object', '');
I think you’ll have to pass along the current posts id as well (or use global $post)..
<?php
function example($field, $postID) {
$post_object = get_field($field, $postID);
if($post_object) {
# get post data
$post = $post_object;
setup_postdata($post);
?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php
# reset postdata
wp_reset_postdata();
}
}
example('my_post_object', $post->ID); //in your template, assuming you do this inside the loop. If outside try replacing $post->ID with get_the_ID()
?>
Hi guys.
@Jonathan – nice code, but I think you need to reference global $post
within the function like so:
function example($field, $postID) {
global $post;
$post_object = get_field($field, $postID);
if($post_object) {
// get post data
$post = $post_object;
setup_postdata($post);
?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php
// reset postdata
wp_reset_postdata();
}
}
example('my_post_object', $post->ID); //in your template, assuming you do this inside the loop. If outside try replacing $post->ID with get_the_ID()
?>
@elliot wouldn’t that be redundant since we’re already passing along the current page/post id?
Hey Guys, thanks a lot the version with the global $post works just fine! Thanks!
Cheers,
mike
Hi @Jonathan
the globla $post is needed for the setup_postdata function to work within a function.
Weird, I know.
The topic ‘Post Object Field doesn't work within a Function’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
Plugin boilerplates can do some of the heavy lifting during initial development. We look at four options to speed up your plugin creation. https://t.co/ZtMsdBxAHw
— Advanced Custom Fields (@wp_acf) June 5, 2023
© 2023 Advanced Custom Fields.
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.