Using WordPress ‘get_the_ID()’ PHP function

The get_the_ID() WordPress PHP function retrieves the ID of the current item in the WordPress Loop.

Usage

$post_id = get_the_ID();

Parameters

  • None

More information

See WordPress Developer Resources: get_the_ID()

Examples

Display Post ID

Display the ID of the current post inside the loop.

while (have_posts()) {
    the_post();
    echo 'Post ID: ' . get_the_ID();
}

Check Post ID for Conditional Output

Display a message if the current post ID matches a specific ID.

$post_id = get_the_ID();
if ($post_id == 123) {
    echo 'This is post 123!';
}

Add Post ID to CSS Class

Add the current post ID to a CSS class for custom styling.

echo '<div class="post post-' . get_the_ID() . '">';
    the_content();
echo '</div>';

Store Post ID in a Variable

Store the post ID in a variable to use it later in your code.

$post_id = get_the_ID();
echo 'The current post ID is: ' . $post_id;

Get Post ID Outside the Loop

Retrieve the post ID when you’re outside the WordPress loop.

global $post;
$post_id = (empty($post->ID)) ? get_the_ID() : $post->ID;
echo 'The post ID is: ' . $post_id;