I am new in wordpress, I was using setup_postdata() method inside of a template file which was being called via shortcode function. I have not used global $post in my function.
if ( ! function_exists( 'new_shortcode' ) ) :
function featured_posts_shortcode( $atts, $content = '' ) {
ob_start();
get_template_part("page-contents/section","abc");
return ob_get_clean();
}
add_shortcode( 'new', 'new_shortcode' );
endif;
Template file code part:
Not Working:
$my_post = get_post($my_post_id);
setup_postdata($my_post); // Does not work.
Working:
$post = get_post($my_post_id);
setup_postdata($post); // Works.
When I use setup_postdata($my_post), it does not set the global post to my post, but when I use setup_postdata($post) it sets the global post to my post.
How can a parameter name can effect a function? Can anyone explain why this is happening?
I am new in wordpress, I was using setup_postdata() method inside of a template file which was being called via shortcode function. I have not used global $post in my function.
if ( ! function_exists( 'new_shortcode' ) ) :
function featured_posts_shortcode( $atts, $content = '' ) {
ob_start();
get_template_part("page-contents/section","abc");
return ob_get_clean();
}
add_shortcode( 'new', 'new_shortcode' );
endif;
Template file code part:
Not Working:
$my_post = get_post($my_post_id);
setup_postdata($my_post); // Does not work.
Working:
$post = get_post($my_post_id);
setup_postdata($post); // Works.
When I use setup_postdata($my_post), it does not set the global post to my post, but when I use setup_postdata($post) it sets the global post to my post.
How can a parameter name can effect a function? Can anyone explain why this is happening?
Share Improve this question asked Feb 18, 2020 at 6:07 MohitMohit 32 bronze badges1 Answer
Reset to default 0As noted in the documentation for setup_postdata()
:
setup_postdata()
does not assign the global$post
variable so it’s important that you do this yourself. Failure to do so will cause problems with any hooks that use any of the above globals in conjunction with the$post
global, as they will refer to separate entities.
So the reason $my_post
doesn't work is that functions you are using are depending on a variable named $post
, but it is not defined. setup_postdata()
does not set this variable. You need to do this yourself by defining $post
, which should be global $post
.