How to get Post ID in Wordpress Admin

2019-03-12 21:15发布

I'm developing a Wordpress plugin and I need to get the current Post ID
in the Write Post / Write Page editing screen (outside the loop).

I also need to do it before the "admin_print_scripts" hook, since I would like to pass some data to a javascript file.

I can't use:

$id = $_GET['post'];

because the url doesn't include this variable when you are adding a new post or page.

So far I've tried these options but none of them worked:

A) This returns an ID of 0

function myplugin_setup() {
    global $wp_query;
    $id = $wp_query->get_queried_object_id();
    var_dump($id);
}

add_action('admin_init', 'myplugin_setup' );  

B) This returns an ID of null

function myplugin_setup() {
    global $wp_query;
    $id = $wp_query->post->ID;
    var_dump($id);
}

add_action('admin_init', 'myplugin_setup' );

C) This also returns an ID of null

function myplugin_setup() {
    global $post;
    $id = $post->ID;
    var_dump($id);
}

add_action('admin_init', 'myplugin_setup' );

7条回答
闹够了就滚
2楼-- · 2019-03-12 22:17

this may work :

$id = get_the_ID();
查看更多
登录 后发表回答