wp_query (and post_id) is empty in admin_init

I’m developing a plugin and one of the issues I am running into is that I cannot get the post id within a function assigned to the admin_init hook.

I tried a few different methods; but, they all seem to use the $wp_query. The ID is not in the URL (SEO URLs).

Read More

Below is a simple version the code I am using. I implemented the code like this just now and ran it by viewing the “post edit” page

add_action('admin_init','do_optional_featured_article');
function do_optional_featured_article()
{
    global $wp_query;
    echo "<pre>";
    print_r($wp_query);
    echo "</pre>";
    die();
}

$wp_query is a mostly empty array, notably, the post member is empty

Following Webord’s advice below, I added this function:

function get_admin_post()
{
    if( isset($_GET['post']) ) 
    {
        $post_id = absint($_GET['post']); // Always sanitize
        $post = get_post( $post_id ); // Post Object, like in the Theme loop
        return $post;
    }
    elseif( isset($_POST['post_ID']) )
    {
        $post_id = absint($_POST['post_ID']); // Always sanitize
        $post = get_post( $post_id ); // Post Object, like in the Theme loop
        return $post;
    }
    else 
    {
        return false;
    }
}

Thanks Webord!!

Related posts

Leave a Reply

1 comment

  1. In the admin, there is not such thing as the current WP_Query, because most of the pages on the admin are not linked to any post, so the pages that have any relation to a post you should grab the ID from the $_GET like that:

    add_action('admin_init','do_optional_featured_article');
    function do_optional_featured_article() {
        if( isset($_GET['post']) ) {
            $post_id = absint($_GET['post']); // Always sanitize
            $post = get_post( $post_id ); // Post Object, like in the Theme loop
            echo "<pre>" . esc_html( print_r( $post, true ) ) . "</pre>"; // Better way to print_r without breaking your code with the html...
            die();
        }
    }
    

    If you are trying to achieve this on a Saving action, the post id should be in $_POST['post_ID'];

    Hope I’ve helped.


    So I’ve changed your code just a little bit more:

    function get_admin_post() {
        $post_id = absint( isset($_GET['post']) ? $_GET['post'] : ( isset($_POST['post_ID']) ? $_POST['post_ID'] : 0 ) );
        $post = $post_id != 0 ? get_post( $post_id ) : false; // Post Object, like in the Theme loop
        return $post;
    }