WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] What exactly is global $post;

[Resolved] What exactly is global $post;

  • devoninternational

    @devoninternational

    Hello I have a question as to why we must declare global $post; before using bits of code such as

    $post->ID, $post->post_parent == '11'

    and other references that use

    $post->

    A real life example below is using a custom field:

    global $post;
    echo get_post_meta($post->ID, 'custom_field_name', true);

    I am just curious as to why you must always declare global $post;

Viewing 4 replies - 1 through 4 (of 4 total)
  • catacaustic

    @catacaustic

    very awesome

    You only have to declare it as global if you’re doing that inside a function/class method that doesn’t have any reference to the $post variable. Some functions do, some don’t.

    As an example, you can do this outside of a functio0n or inside one of yor template files (template files have got access to the $post variable):

    echo get_post_meta($post->ID, 'custom_field_name', true);

    But inside of a function, you need to call it as global because there’s no reference to the $post variable inside the function.

    function test_print_meta () {
        global $post;
        echo get_post_meta($post->ID, 'custom_field_name', true);
    }
    devoninternational

    @devoninternational

    Great info,

    what exactly do you mean when you say: (template files have got access to the $post variable)

    Is this different than page template files? Or do you mean page template files. I have functions in my page template files but have to use global $post as you stated above.

    Thanks again for the solid info!

    catacaustic

    @catacaustic

    very awesome

    Template files are for pages, posts and everything else, so I don’t discriminate by saying “page” templates only. 🙂

    As I said before, functions don’t have access to that variable. Functions are encapsulated, like closed in little balls – they only know what’s inside themselves and nothing from outside this. This means that any function anywhere doesn’t automatically know about the $post variable and it needs to be declared as global before it can be used. This applies to functions used anyhwere and in any file. The template file shav eaccess to that variable because they aren’t enclosed in functions (well, strictly speaking they are, but the global is called before your template file is included in the script so the code knows about it before your template is loaded).

    devoninternational

    @devoninternational

    Great write up thanks for this.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘[Resolved] What exactly is global $post;’ is closed to new replies.
Skip to toolbar