Please keep in mind, that all method below works for WordPress pages and custom post types too.
If you are looking for information how to do the opposite – get post by ID, all you need is to use get_post()
function, example:
$post = get_post( 12 );
// let's get a post title by ID
echo $post->post_title;
Or you can get post by ID with WordPress WP_Query
too:
$query = new WP_Query( array( 'p' => 12 ) );
$query->the_post();
// let's get post type by ID
echo $query->post->post_type;
// Get post status by post ID
echo $query->post->post_status;
- From the Global $post object
Please note: All the following examples require some basic PHP knowledge. But if you have not enough knowledge — do not be afraid of trying.
Global object $post
contains a lot of data of the current post. It is very easy to get ID from the object:
echo $post->ID;
Sometimes, when you are using it inside a function (or in any case when it prints nothing 🙂 just add global $post;
line of code at the beginning.
global $post;
echo $post->ID;
2. Using get_the_id() and the_id() functions
The difference between this two functions is that get_the_id()
returns ID of the current post, and the_id()
prints it.
echo get_the_id();
the_id();
3. Get Post ID by Title
This is a build-in WordPress function and since 3.0.0 version it works not only for pages but for any custom post type. Third function parameter is the name of a post type (page
by default).
$mypost = get_page_by_title( 'Hello World', '', 'post' );
echo $mypost->ID;
4. Get Post ID by Slug
The function is similar to get_page_by_title()
. But if your post has parent (for hierarchical post types only) you have to specify parent slug as well, for example parent-post/hello-world
.
$mypost = get_page_by_path('hello-world', '', 'post');
echo $mypost->ID;
5. Get Post ID by URL
Very simple function.
$mypost_id = url_to_postid( 'https://jslib.dev/wordpress/get-post-id.html' );
echo $mypost_id;
6. Get Post ID in a WP_Query loop
When you use WP_Query or another additional loops it is always much better and faster to get the $post object properties instead of using get_the_id()
or the_id()
functions.
$your_custom_query = new WP_Query( 'posts_per_page=10' );
while( $your_custom_query-have_posts() ) : $your_custom_query->the_post();
echo $your_custom_query->post->ID; // print post ID
endwhile;