get_the_ID()

Retrieve the ID of the current item in the WordPress Loop.


Return Return

(int|false) The ID of the current item in the WordPress Loop. False if $post is not set.


Top ↑

Source Source

File: wp-includes/post-template.php

function get_the_ID() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
	$post = get_post();
	return ! empty( $post ) ? $post->ID : false;
}


Top ↑

Changelog Changelog

Changelog
Version Description
2.1.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Craigbavender

    Should be noted that if this is ran on the Blog homepage, it instead returns the first listed Post ID instead of the blog homepage ID.

  2. Skip to note 2 content
    Contributed by Codex

    Post Anchor Identifier
    get_the_ID() can be used to provide a unique anchor in a script. For instance, a dynamically-generated drop down menu with actions for each post in an archive could have

    <?php
    	$id = get_the_ID();
    	$dropdown = "<select name='dropdown-".$id."' >";
    	$dropdown .= "<option id='option1-". $id ."'>Option 1</option>";
    	$dropdown .= "</select>";
    ?>
    

    This would allow us to use JavaScript to control the element as it has a unique ID, and when submitting it as a form through the POST or GET methods the dropdown box will be sent with a unique ID which allows the script to note which post it is working on. Alternatively a hidden variable could be sent which will allow the script to see which post the submission is referring to

    <?php
    	echo '<input type="hidden" name="activepost" id="activepost" value="'.get_the_ID().'" />';
    ?>
    

You must log in before being able to contribute a note or feedback.