WordPress at a glance

get_the_ID() WP 2.1.0

Retrieve the ID of the current post in the WordPress Loop. Can be used only inside the loop.

Post ID in the loop can be also obtained through $post->ID. Sometimes it's easier and there is no unnecessary call of the function.

Is the basis for: the_ID()
Works based on: get_post()
✈ 1 time = 0.000037s = very fast | 50000 times = 0.28s = very fast PHP 7.1.2, WP 4.7.3

No Hooks.

Return

Int/false. The ID of the current item in the WordPress Loop. False if $post is not set.

Usage

get_the_ID();

Examples

#1 Get the post ID

Usually the post ID inside the loop can be obtained through $post->ID, but in some cases it may be useful to get it like this:

$post_id = get_the_ID();
// $post_id will contain the ID of the current post in the loop

#2 Display the meta field of the post using the get_the_ID() function:

$post_id = get_the_ID();
echo get_post_meta( $post_id, 'meta_key', 1);

// or can be so:
echo get_post_meta( get_the_ID(), 'meta_key', 1);

Code of get_the_ID: wp-includes/post-template.php VER 4.9.8

<?php
function get_the_ID() {
	$post = get_post();
	return ! empty( $post ) ? $post->ID : false;
}

Related Functions

From tag: WP Loop

More from category: Posts, pages...

No comments
    Hello, !     Log In . Register