To make it possible to access the data in the database, every element on your website has an ID value. With this ID, you can call, edit or delete your item. This makes it possible to perform the necessary operations to show your website to a visitor. In this article, we will explain how you can find the ID values of the elements without using plugins on your site.
Finding the page ID without a plugin
If you want to find the ID value of a page in WordPress, first go to the Pages > All Pages tab.
Open the editing interface by clicking the Edit button on the page you want to know the ID value.
When you check the URL on the Edit page, the numeric value after the post= statement is the ID value of your page. As can be seen in the image below, the value of the Homepage page is 6.
Finding the tag or category IDs without a plugin
You can also use the above process for categories and tags. To find the tag ID value, go to Posts > Tags page.
In the list here, hover over the tag you want to learn and press the Edit button.
When you look at the URL of the page, the value next to tag_id= is the ID of your tag.
Examples of using the ID values in the codes
Code that prints the ID of the current page
You can add the following code to the relevant PHP file to print the ID of the current page on that page.
<?php echo get_queried_object_id(); ?>
A shortcode that lists the last five posts in the selected category
It is possible to access the posts in the category with their ID values. In the code example below, if you replace the 13 value in the $category_id variable with the desired category ID value, it will list the last 5 posts in that category.
Just add the code below to the functions.php file and save it. To use the code, you can use the shortcode on any page or widget you want.
function last_five_posts()
{
$category = single_term_title("", false);
$category_id = 13;
$args = array(
"numberposts" => 5,
"category" => $category_id,
);
$posts = get_posts($args);
$content = "";
if( have_posts() ) {
foreach($posts as $post){
the_post();
$link = get_permalink();
$title = get_the_title();
$content .= "<li><a href='$link' >$title</a></li>\n";
}
}
return $content;
}
add_shortcode('last_five_posts', 'last_five_posts' );