我需要在循环外获取 WordPress 插件页面中的当前 page id
。我为获取当前 page id
编写的代码在我的插件页面中。我尝试了很多代码,但不起作用
$page_object = get_queried_object();
$page_id = get_queried_object_id();
// "Dirty" pre 3.1
global $wp_query;
$page_object = $wp_query->get_queried_object();
$page_id = $wp_query->get_queried_object_id();
但这对我不起作用。
global $post;
echo "pageid: ".$post->ID;
这也行不通。
当我尝试
global $wp_query;
$post_obj = $wp_query->get_queried_object();
$Page_ID = $post_obj->ID;
echo $Page_ID;
然后出现错误信息
Fatal error: Call to a member function get_queried_object() on a non-object in H:\xampp\htdocs\wordpress\wp-content\plugins\wpk\wpk.php on line 876
当我打印时:
global $wp_query;
print_r($wp_query);
那么结果是:
WP_Query Object
(
[query] =>
[query_vars] => Array
(
)
[tax_query] =>
[meta_query] =>
[date_query] =>
[queried_object] =>
[queried_object_id] =>
[request] =>
[posts] =>
[post_count] => 0
[current_post] => -1
[in_the_loop] =>
[post] =>
[comments] =>
[comment_count] => 0
[current_comment] => -1
[comment] =>
[found_posts] => 0
[max_num_pages] => 0
[max_num_comment_pages] => 0
[is_single] =>
[is_preview] =>
[is_page] =>
[is_archive] =>
[is_date] =>
[is_year] =>
[is_month] =>
[is_day] =>
[is_time] =>
[is_author] =>
[is_category] =>
[is_tag] =>
[is_tax] =>
[is_search] =>
[is_feed] =>
[is_comment_feed] =>
[is_trackback] =>
[is_home] =>
[is_404] =>
[is_comments_popup] =>
[is_paged] =>
[is_admin] =>
[is_attachment] =>
[is_singular] =>
[is_robots] =>
[is_posts_page] =>
[is_post_type_archive] =>
[query_vars_hash] =>
[query_vars_changed] => 1
[thumbnails_cached] =>
[stopwords:WP_Query:private] =>
)
我不知道如何解决这个问题,如何获取当前的页面id
。如果你知道如何解决这个问题,那么我需要你的支持。提前致谢。
最佳答案
get_the_ID();或 $post->ID;
返回 Wordpress 中的当前页面或帖子 ID。
But you need to ensure that your post is saved in wordpress post table. Other wise you can't get the id , simply because of it is not an entry in wordpress database.
如果它是一个静态页面并且它不是 wordpress 帖子中的条目,那么 get_the_ID()
没有返回任何内容。
例如:get_the_ID() 不适用于帖子存档页面、wordpress 后端的管理页面等。
所以 根据这个问题,您正在尝试获取作为后端插件设置页面或任何存档页面的页面的 ID。
更新
Method to get the current post id in wordpress
(1) 全局 $post; $post->ID();
(2) 全局 $wp_query; $post_id = $wp_query->get_queried_object_id();
(3) 全局 $wp_query; $post_id = $wp_query->post->ID;
(4) get_the_ID();
[ 建议此标签必须在循环内。 ]
看到这个
function get_the_ID() {
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
即 get_the_ID() 返回当前 $post 的 id。
(5) get_query_var('page_id')
[如果我们使用漂亮的永久链接,它将无法工作]
https://codex.wordpress.org/Function_Reference/get_query_var
关于php - 获取wordpress插件页面中的当前页面ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22351038/