最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

theme development - Local variable name in setup_postdata()

programmeradmin0浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 0

As 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.

发布评论

评论列表(0)

  1. 暂无评论