1

If I call get_the_ID() multiple times throughout my file, would it be better performance wise to assign get_the_ID() to a variable?


// Call get_the_ID() directly
function_that_needs_post_ID( get_the_ID() );    
another_function_that_needs_post_ID( get_the_ID() );

VS

// Assign get_post_ID() to variable
$post_id = get_the_ID();    
function_that_needs_post_ID( $post_id );
another_function_that_needs_post_ID( $post_id);
  • In this simple example (two references), you'll never notice a difference. If you are inside a 500K iteration loop, then you might. Also, if a significant number of calls to the WP function it is always good to read the source code to see if it is hitting the database...that may guide your decision as well. – C C Aug 12 '16 at 13:14
  • 1
    get_the_ID() calls get_post() which invokes $GLOBALS['post']. So, no new database call is made. – RRikesh Aug 12 '16 at 13:17
4

Yes, it is always better to keep the result of a function call in a private variable. But the reason is not performance.

Reliability

In your example, you are calling a function that internally accesses a global variable ($post). A global variable can be overwritten any time, so you might end up with two different post IDs, because some other code changed the variable between your two calls.

Consistency

The function get_the_ID() returns either a positive integer or a boolean (false). That's terrible, because it forces you to either cast the value to an integer, if you are striving for "ifless" code, or you have to decide what to do after each call again, so you get a lot of repetitive code.

Alternative implementation

I would suggest that you make your functions methods of a class, then pass (or setup) the ID in the constructor and save it internally. That will reduce the static dependency, and if WordPress ever changes this part, you have only one piece of code to fix.


The performance issue with get_the_ID() is hidden in WP_Post::filter(). But that's so minor, you can safely ignore it.

| improve this answer | |
  • On the reliability point, it can go both ways. If the value should be updated due to some other process changing it, then you will have an outdated value held in your private variable, which can cause unintended side effects that can be hard to track down. You have to look at every situation, carefully. – C C Aug 12 '16 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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