How to get post ID in WordPress?

Several posts and pages in WordPress are uniquely identified by their IDs. Once you know the ID of a post, you can get other relevant information like the title or publication date, etc.

In this post, I will show you two methods to get post ID in WordPress.

Using the get_the_ID() Function to get the post ID

You can easily get the current post ID in the WordPress loop using the get_the_ID() function. This function returns the ID of the current post in the WordPress loop or return false if the $post the variable is not set.

You may be wondering what I mean by WordPress loops. The WordPress loop is one of the techniques used to display the contents of a post within template files.

If you want to learn basic PHP coding for WordPress, check out our free course.

You can also find many WordPress coding tutorials here on Envato Tuts +.

Here is an example that gets the current post ID in WordPress:

The above fragment comes from single.php file in the Storefront theme. I changed it to echo the post ID before the post content.

Let’s say you have an FAQ page within the theme with the file name page-faqs.php. You will be able to use the same get_the_ID() function to get the page ID.

I would also like to add that you can usually get the post ID using this function outside of the loop as well. However, it may not always be accurate.

Using get_queried_object_id() Function to get the page ID

Another function you can use to get the ID of any required object like a post or page ID in WordPress is the get_queried_object_id() function. This function will give you the ID of the current post or page even outside the loop.

This feature is especially useful on pages like the blog home page. In this case, using the function get_the_ID() will return the ID of the first blog post in the loop.

For my website, I set the blog home page to be /blog/. Now, the ID of this page is 134. The ID of the first post listed on the blog page is 192. If I call the function get_the_ID() on this page, it will return 192. What I actually want here is the value 134.

Try adding the following lines on your blog home page and you will see different IDs generated by these functions.

Putting the above code after the last post in the loop would have resulted in the output of get_the_ID() function being the ID of the last post. The function get_queried_object_id() it would still return the correct page ID.

If you use this function on the category archive page, it will return the category ID instead because there is no specific category page.

Final thoughts

In this quick tip, we learned about two different functions you can use to get the current post or page ID in WordPress. You can also get the post ID using the global $post object but will not always be reliable as someone may have changed its value.

Source link

By LocalBizWebsiteDesign

Leave a Reply

Your email address will not be published. Required fields are marked *