Every element of WordPress has its own ID. An ID is a unique number associated with each element. For example, each post has a unique post ID. Similarly pages have page ID, categories have category ID, tags have tag ID and comments have comment ID.
All these IDs are unique for each element. IDs are how WordPress organizes all the content in the MySQL database. With the ID, we can identify these elements.
Many times, we need these IDs for development or other purposes. Let’s see how to find IDs of posts, pages, categories, tags, users and comments in WordPress.
(Image : 123rf.com)
Finding the IDs in WordPress
To find post ID, go to the “Posts” section in the WP-admin and click on the edit link below the post.
Now the post editor page will open. Observe the URL carefully. That URL has parameter post=. That’s the post ID.
For instance, in this image, the post id is 2664.
The exactly same is there for pages, media and custom post types.
For categories, go to the “Categories” section under Posts. Click on edit link below the category you want.
In the URL opened, there is a parameter, tag_ID=. Its value is the category ID.
For example, in this image, the category ID is 6.
Follow the same procedure for tags and other custom taxonomies.
For users, go to “users” section, click on the user you want to know the ID of. See the user_id= parameter in the URL. Its value gives us the user ID of any user.
For comments, go to the edit link of any comment you want. In the URL, the parameter named “c=” gives us the comment ID.
PHP codes for advanced users and developers
Get Post ID by name :
<?php $post_query = get_page_by_title('The exact title here. It is case-sensitive'); echo $post-query->ID; ?>
Get Post ID by slug (permalink) :
<?php $post_query = get_page_by_path('the-exact-slug'); echo $post-query->ID; ?>
Get category ID by name :
<?php $my_cat_id = get_cat_ID('The Category Name'); echo $my_cat_id; ?>
Get category ID by slug :
<?php $cat_query = get_category_by_slug('category-slug'); echo $cat_query->term_id; ?>
Get tag ID by name :
<?php $tax_query = get_term_by('name', 'Tag Name', 'post_tag'); echo $tax_query->term_id; ?>
Get tag ID by slug :
<?php $tax_query = get_term_by('slug', 'tag-slug', 'post_tag'); echo $tax_query->term_id; ?>
For custom taxonomies, replace the third parameter
post_tag with the slug of your custom taxonomy.
Get user ID by username :
<?php $user_query = get_userdatabylogin('my-username'); echo $user_query->ID; ?>
Get user ID by email :
<?php $user_query = get_user_by( 'email', 'firstname.lastname@example.org' ); echo user_query->ID; ?>
Get user ID by author slug :
<?php $user_query = get_user_by( 'slug', 'author-slug' ); echo user_query->ID; ?>
So, these were the different methods for determining the IDs of different elements of WordPress. You can find references to all the PHP functions used here at WordPress Codex.
I hope this post helped you. In case you have any doubt, query or suggestion, do not hesitate to drop a comment below.