在很多的 WordPress 主题或者插件功能的开发中,我们总是需要获取到 WordPress 给每个页面定义的 ID,不然也某些情况下是无法确定这是哪一个页面,针对于文章或者页面的 ID 获取基本可以使用 get_the_ID()这个函数来直接获取,但是在循环外该函数是无法获取到值的。

WordPress 页面 ID 获取

那么下面子凡就根据在 Fanly MIP 主题开发中遇到的情况下,收集整理了几个方法:

方法一:

1
2
3
//文章或页面的 ID 值,如果未在循环中输出值可能不准确
$postid = get_the_ID();  
echo $postid;

方法二:

1
2
3
//检索当前查询对象的 ID
$current_id = get_queried_object_id();  
echo $current_id;

方法三:

1
2
3
4
// 检索当前查询的对象,从对象中获取 ID
$object = get_queried_object();
$id = $object -> ID;
echo $id;

方法四:

1
2
3
4
// 通过$post 全局变量获取文章或页面 ID
global $post;
$id = $post -> ID;
echo $id;

补充内容:

1
2
3
4
5
6
7
8
9
10
// 第一种获取父级页面的 ID
global $post;
$id = $post -> ID;
$parent = get_post_ancestors($post -> ID);
print_r($parent);//打印出 Array ( [0] => 101 ) 
 
// 第二种获取父级页面的 ID
global $post;
$parent_id = $post -> post_parent;
echo $parent_id;//打印出父级页面的 ID

其实究竟要怎么去获取还是需要根据实际的开发情况而确定,文章或页面或者循环中可以使用 get_the_ID 函数直接获取,如果需要某些特殊或者 get_the_ID 获取不正确的时候,子凡觉得使用 get_queried_object_id 函数也就足够了,至于其它的方法大家自己研究吧!

泪雪博客原创文章:https://zhangzifan.com/wordpress-get-id.html

发表评论
登录后参与评论
专注 WordPress 网站优化解决方案! 加入我们