Khalil Ghâñmî

0 %
Khalil Ghâñmî
Développeur full-stack
  • Residence:
    Tunis
  • City:
    Bardo
  • Age:
    30
French
English
arabe
  • HTML 5 / CSS 3
  • Bootstrap
  • JavaScript / Jquery/Ajax
  • ReactJS
  • API
  • Angular
  • PHP/Mysql
  • Python
  • Java
  • Wordpress
  • OpenCart
  • Illustrator | Photoshop | Premier Pro | Animate
  • OVH | Godaddy | Vipdomaine | Zenhosting | LWS | Hostgator
  • Cpanel
  • Google Search | Google sheets | Google docs | Office

Retrieve the ID of a post or a page in WordPress

25 August 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 Non classé, PHP, worpdressTags:
Write a comment