• Resolved pandglobal

    (@pandglobal)


    for some reasons i still don’t know why global $wp_query; is returning empty arrays. the index keys are showing but the values are all empty.

    I tried doing
    ~~~
    global $wp_query;
    print_r($wp_query);
    ~~~
    and i got empty values.

    I have tested
    ~~~
    // Get Current Page ID outside Loop
    global $wp_query;
    $post_obj = $wp_query->get_queried_object();
    $Page_ID = $post_obj->ID;
    echo $Page_ID;
    ~~~

    yet is not working, what am i doing wrong? as i want to use it in my custom plugin

Viewing 6 replies - 1 through 6 (of 6 total)
  • Prashant Singh

    (@prashantvatsh)

    Thread Starter pandglobal

    (@pandglobal)

    i have tried all i saw in the link you quoted above but none is working.
    get_the_ID() throws undefined function, $wp_query is empty.

    suppose i want to loop or do anything what should i do?

    Moderator bcworkz

    (@bcworkz)

    If your code has not hooked into an action and simply exists in your plugin’s .php file, then it’s executing too early. Initial plugin code executes very early in the loading process, before WP is stable. Code should generally be hooked into “init” action or later. For queries, try the “parse_query” action.

    Getting the queried object ID does not always return a page ID. It does do so for singular page requests.

    Thread Starter pandglobal

    (@pandglobal)

    thanks @bcworkz i was able to get the $wp_query data using parse_query action and i can echo current page id using

    this is the exact code i used
    ~~~
    add_action(‘parse_query’, ‘showid’);
    function showid(){
    global $wp_query;

    $theid = !empty($wp_query->queried_object->ID) ? $wp_query->queried_object->ID : ”;

    echo $theid;
    }

    ~~~

    the problem there is that if i use echo $theid in the function above it shows the page id but if i use return $theid in the function it won’t show anything.
    even if i do
    ~~~
    $my = showid();
    echo $my;
    ~~~

    it still don’t show. only works when i use echo but i don’t want it printing out on any pages i just want to use the value and echo it any time i wish to.

    Moderator bcworkz

    (@bcworkz)

    Ah yes, your $theid is out of scope to other code outside of the action callback. You need to declare it a global value or set a static class property for it to be available to other code. In PHP, the global keyword must be used both when the variable is initialized and again within scope of where you want to get the value.
    https://www.php.net/manual/en/language.variables.scope.php

    Thread Starter pandglobal

    (@pandglobal)

    oh thanks alot, your response was helpful

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘How to get current page id’ is closed to new replies.