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).
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!!
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: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: