Khalil Ghâñmî

0 %
Khalil Ghâñmî
Front-end developer
  • Residence:
    Tunis
  • City:
    Bardo
  • Age:
    28
French
English
arabe
HTML 5 / CSS 3
JavaScript / jquery
PHP / MYSQL
WordPress
OpenCart 3
Vegas Pro
Adobe premier pro
  • Bootstrap, Materialize
  • Stylus, Sass, Less

Retrieve the ID of a post or a page in WordPress

25 août 2022

You may be using WordPress to publish your blog.

You have started to modify a theme to adapt it to your needs/tastes/desires but a variable resists you: the variable which allows you to display a post thanks to a unique number identifying it (ID).

By default, this identifier is only available inside the WordPress Loop:

/* on affiche le numéro de post/page dans la boucle WordPress */
the_ID();

As long as you are in the loop, no worries.

On the other hand, if you want to write your own plugin or use this variable in your sidebar, you are a bit stuck because the_ID() is then no longer a valid function.

To remedy this problem, you can use the $post->ID variable to return the post or page number.

Take a look at the following code:

/* on fait de $post une variable globale */
global $post;

/* on stocke la variable dans un nom de variable inutilisé */
$sky_post_ID = $post->ID;

/* on affiche cette variable */
echo $sky_post_ID;

Alternative, by performing a simplified SQL query by $wp_query.

This method is used mostly out of the loop, working directly on the database:

/* on fait de $wp_query une variable globale */
global $wp_query;

/* on stocke la variable dans un nom de variable inutilisé */
$sky_post_ID = $wp_query->post->ID;

/* on echo cette variable */
echo $sky_post_ID;

That’s it, you should now be able to access those famous post id and page id.

Happy coding 🙂

Posted in PHP, worpdress
Write a comment