如何在 Wordpress Admin 中获取帖子 ID [英] How to get Post ID in Wordpress Admin
问题描述
我正在开发一个 Wordpress 插件,我需要获取当前的帖子 ID
在写帖子/写页面编辑屏幕(循环外).
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).
我还需要在admin_print_scripts"挂钩之前执行此操作,因为我想将一些数据传递给 javascript 文件.
I also need to do it before the "admin_print_scripts" hook, since I would like to pass some data to a javascript file.
我不能使用:
$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) 这将返回 0 的 ID
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) 这将返回一个空 ID
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) 这也返回一个空 ID
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' );
推荐答案
确保在 WordPress 查询后调用全局 $post.如果您向 init 或 admin_init 添加操作,则查询尚未就绪,因此您无法从全局 $post 变量中获取任何信息.
Make sure you call the global $post after the WordPress query. If you add an action to init or admin_init, the query isn't ready so there's nothing you can get out of the global $post variable.
我的建议是检查此页面的操作参考:http://codex.wordpress.org/Plugin_API/Action_Reference 并选择适合您的一个.
My advice would be to check the action reference from this page: http://codex.wordpress.org/Plugin_API/Action_Reference and choose one that works for you.
例如,我是这样做的:
add_action( 'admin_head', 'check_page_template' );
function check_page_template() {
global $post;
if ( 'page-homepage.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
// The current page has the foobar template assigned
// do something
}
}
并且我能够在 WP admin 中获取页面 ID
And I was able to get the page ID in WP admin
这篇关于如何在 Wordpress Admin 中获取帖子 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!