Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Right now I am using:

$wp_query->post->ID;

I want to know if there is a better way for getting the post id that consumes less resources?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

An alternative to your way would be to access the $post global:

global $post
echo $post->ID;

But

  1. It won't make a noticeable difference, either way
  2. If you want to increase efficiency, you ought to be looking elsewhere...

EDIT, pertaining to comments:

what about get_the_ID();?

--> Needs to be run inside the Loop.

i have tried both options (get_the_ID and accessing $post global) both give me a wrong id.

If the latter is the case, you, or some plugin you are using, has not properly reset postdata.

You say to look elsewhere... where should I be looking?

I have no idea what it is you are writing. But if you experience resource bottlenecks or inefficiency, retrieval of the current post ID is likely not the cause.

share|improve this answer
    
just checked, so I can safely keep using $wp_query->post->ID; ? And, if I want to use your way, I can put <?php wp_reset_postdata(); ?> before global $post –  Gixty Sep 17 '13 at 21:06
    
Well, the resetting of the post global should happen after whatever secondary loop modified the global. But essentially, yep, your above assumptions are correct. –  Johannes Pille Sep 17 '13 at 22:05
    
great! Thank you for clarifrying. –  Gixty Sep 17 '13 at 22:07

You can also use get_queried_object_id() in conjunction with is_main_query() outside the Loop

if ( is_main_query() )
    $mypostid = get_queried_object_id();

Note that this function will return author id on a archive page, category id on a category archive, etc.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.