How to return the post ID in a WordPress shortcode

This should be so simple and it was it once I found the solution! (duh)

All I wanted to do is create a shortcode that will print (or echo or return – whatever you want to call it) the post ID of the current post.

So I would type something like: [mypostid]

and when the post was saved it would display just the post ID like: 1234

I tried using ‘the_ID’ and ‘get_the_ID’ and even $id, but none of those things worked.

I couldn’t find a straightforward answer to this question so I’m going to share the solution here. It’s really simple!

How to display the post ID in a shortcode:

You can put the code for this function in to the functions.php file of your theme, or preferably, add it to a plugin (details below). With a plugin you won’t lose the functionality of your shortcode if/when you change your WordPress theme.

*It’s a good idea to make a general Custom Functions plugin that is specific to your website and you can use it to house all these little extra functions that you will accumulate over time.

Here’s the basic code for the post ID shortcode:

//[thepostid]
function thepostid_func( $atts ){
         global $post;
         return $post->ID;   
}
add_shortcode( 'thepostid', 'thepostid_func' );

And below is the code to make a plugin out of this function. You should add this code to a plain text file called something like ‘my-custom-functions-plugin.php’, then either upload it to ‘wp-content/plugins/my-custom-functions-plugin/’ via FTP or, add the my-custom-functions-plugin.php file to a .zip file and upload it using the upload feature on the WordPress ‘Add New’ plugin page.

<?php
/*
Plugin Name: My Custom Functions
Plugin URI: http://yourwebsiteaddress.com
Description: A custom site functions plugin for yourwebsiteaddress.com
Version: 1.0
Author: Your Name Here
*/
 
//[thepostid]
function thepostid_func( $atts ){
         global $post;
         return $post->ID;   
}
add_shortcode( 'thepostid', 'thepostid_func' );

So, once you’ve added the code to your theme or plugin, you can simply type [thepostid] in to any post or page and voila! – the post ID will be displayed.