WordPress Gets the current page ID of several methods

https://zhangzifan.com/wordpress-get-id.html

 

In many developing WordPress theme or plug-in function, we always need to get WordPress ID to each page defined, otherwise it is impossible to determine in some cases this is a page which, to obtain the ID of the article or page basic can be used get_the_ID () function to obtain directly, but the function can not be obtained outside the loop value.

WordPress page ID acquisition

Then the following on the case of the child who encountered in Fanly MIP theme development, collected several methods:

method one:

1
2
3
ID value // article or page, if the output value is not in the cycle may be inaccurate
$postid = get_the_ID();  
echo $postid;

Method Two:

1
2
3
// Retrieve the current query object ID
$current_id = get_queried_object_id();  
echo $current_id;

Method three:

1
2
3
4
// retrieve an object of the current query, to get the ID from the object
$object = get_queried_object();
$id = $object -> ID;
echo $id;

Method four:

1
2
3
4
// Get the ID article or page through the global variable $ post
global $post;
$id = $post -> ID;
echo $id;

to add on:

1
2
3
4
5
6
7
8
9
10
// get the first page of the parent ID
global $post;
$id = $post -> ID;
$parent = get_post_ancestors($post -> ID);
print_r ($ parent); // Print out Array ([0] => 101) 
 
// get the ID of the second parent of the page
global $post;
$parent_id = $post -> post_parent;
echo $ parent_id; // print out the ID of the parent page

In fact, exactly how you want or need to get determined based on the actual development, the article or page, or you can use the loop function get_the_ID direct access, or if you need some special get_the_ID not get the right time, every child will feel that the use get_queried_object_id function enough, as other methods we all study it!

Unless otherwise noted, are the tears of snow blog original article, reproduced in any form is prohibited

This link: https://zhangzifan.com/wordpress-get-id.html

Guess you like

Origin blog.csdn.net/james_laughing/article/details/92382402
Recommended