get_the_ID(): int|false
Retrieves the ID of the current item in the WordPress Loop.
Return
int|false The ID of the current item in the WordPress Loop. False if $post is not set.
Source
File: wp-includes/post-template.php
.
View all references
function get_the_ID() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
$post = get_post();
return ! empty( $post ) ? $post->ID : false;
}
Changelog
Version | Description |
---|---|
2.1.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
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.
Top ↑
Feedback
If you are looking for conditional checks (i.e. if its this page, do this), is_single() checks if its the single post version of an ID. There are also other for homepage, page, etc. Check the other conditionals for others: https://codex.wordpress.org/Conditional_Tags — By michaeldhayes —
In some cases, such as when you’re outside The Loop, you may need to use
get_queried_object_id() instead of get_the_ID().
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 haveThis 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
If you are working with custom post types or you are just not sure if the file you are working in has any direct access to the post, you can try this handy statement to get the ID of a post; outside of the loop even.
Then use $post_id string to assure you have the post ID. Example usage:
Store the ID
The ID can be stored as a variable using