• Resolved farnely

    (@farnely)


    I’m confused about the bext way to get the post ID inside a WP_Query loop. Of the two methods below, I’ve read that the first is less prone to error than the second but also less efficient. Is this correct? Which is the best one to use please?

    Method One

    $query = array( 
        'post_type' => 'my-custom-post-type',
        'post_status' => 'publish'
    );
        
    $result = new WP_Query( $query );
    if ( $result->have_posts() ) {
        while ( $result->have_posts() ) {        
            $result->the_post();
            $result_id = (int) get_the_ID();		
        }
    }
    wp_reset_postdata();

    Method Two

    $query = array( 
        'post_type' => 'my-custom-post-type',
        'post_status' => 'publish'
    );
        
    $result = new WP_Query( $query );
    if ( $result->have_posts() ) {
        while ( $result->have_posts() ) {        
            $result->the_post();
            $result_id = (int) $result->post->ID;	
        }
    }
    wp_reset_postdata();

    Many thanks

Viewing 3 replies - 1 through 3 (of 3 total)
  • Joy

    (@joyously)

    In your example, you have called the_post(), so the global $post variable is being used. The get_ functions use the global $post, so neither one is more correct. If your code was not “for the loop”, obviously a direct access of the variable is fast and correct, and the get_the_ID call would be the wrong post.

    Moderator bcworkz

    (@bcworkz)

    “less efficient” in this case is technically correct, but the difference is so negligible that it makes no difference in real world performance. Maybe if you were looping through thousands of items the difference might start to add up. If your loop source were that big, you’d have bigger performance issues ?? In the proper context, I like to use get_the_ID(), others don’t, the choice is more a matter of coding style.

    Thread Starter farnely

    (@farnely)

    Thank you both for your replies; that’s been a great help

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘WP_Query Clarification please’ is closed to new replies.