2

This is my code.

/*
    Plugin Name: 
    Plugin URI:  
    Description: 
    Version:     
    Author:      
    Author URI:  
    License:     
    License URI: 
    Text Domain: 
    Domain Path: 
    */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$page_object = get_queried_object();
var_dump($page_object);

$page_id = get_queried_object_id();
echo $page_id;

I am geting >> Fatal error: Call to a member function get_queried_object() on a non-object in C:\wamp\www\wordpress\wp-includes\query.php on line 45

1 Answer 1

3

Take a look at the Plugin API/Action Reference, particularly the section Actions Run During a Typical Request.

In WordPress, you're going to want to hook your code to various specific points of execution, otherwise it will be executed immediately, which is often not the desired result.

The code you posted is going to be executed as soon as the plugin is loaded, which takes place on the plugins_loaded hook. That's way too early in the flow of loading a page (for example) to be getting a post/page ID.

Below, I've wrapped your code in a function that is hooked to the template_redirect hook and now it generates the expected results.

add_action( 'template_redirect', 'wpse_inspect_page_id' );
function wpse_inspect_page_id() {
    $page_object = get_queried_object();
    var_dump($page_object);

    $page_id = get_queried_object_id();
    echo $page_id;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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