function to get the post id in while (have_posts()) : the_post();

Created at 26-Aug-2023 , By samar

Within the WordPress loop using have_posts() and the_post(), you can directly get the current post's ID using the get_the_ID() function. This function returns the ID of the current post in the loop.

Here's an example of how to use it:

while (have_posts()) : the_post();

   $post_id = get_the_ID(); // Get the current post's ID

   // Rest of your loop code
   // ...


In this code, $post_id will hold the ID of the current post as you loop through the posts using have_posts() and the_post(). You can use this ID for various purposes within the loop.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.