Posts Tagged ‘$post->ID’

Retrieving the current $post->ID on hook ‘init’

Thursday, November 17th, 2011

Within a WordPress theme it’s no problem to get the current post_id,
but when it’s plug-in code which is hooked to the ‘init’ event – object $wp_query doesn’t exist yet.
Following example demonstrates how to get the ID, even when permalinks are enabled:

function get_the_post_id() {
   global $wpdb;
   $slug = str_replace("/","",$_SERVER['REQUEST_URI']);
   $sql = "
      SELECT
         ID
      FROM
         $wpdb->posts
      WHERE
        post_name = \"$slug\"
   ";
   return $wpdb->get_var($sql);
}

When permalinks are disabled, it’s no problem at all to get the current $post->ID.