0

This question already has an answer here:

Sorry if this sounds like a dumb question but it's something that has bugged me for a while. I need some explanation on

function custom_function () {
    global $post;
}

I understand from PHP that a global variable is available is used to access global variables from anywhere in the script. I know global $post usually set when a new query is being set. What would happens if global variable is not declared in case of WordPress query posts? I know how to use it in WordPress but have not fully understand why. Thank you.

marked as duplicate by Jacob Peattie, Jack Johansson, Dave Romsey, cjbj, Brian Fegter Dec 4 '17 at 16:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

The global $post; command acts similar to the_post() function, but outside the loop.

When you want to use post's data such as get_the_ID() or the_title() and you are not in the loop, you can use the global $post; to access these data. After so, you can have access to them, such as $post->ID or $post->post_title. This way, you can use the above functions as follows:

get_the_title( $post->ID );

In a loop, you can use the the_post() function to do this:

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        // Now you can use the_ID(); for example
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.