2

When using the 'fields' => 'ids' parameter, is it better to create a new WP_Query in the code below rather than doing get_posts?

How would the loop look if I used WP_Query?

function myplugin_delete_image_items( $postid ) {

    $args = array(
        'post_type'     => 'myplugin_image_item', 
        'cache_results' => false,   // Disable caching, used for one-off queries
        'no_found_rows' => true,    // We don't need pagination, so disable it
        'fields'        => 'ids',   // Returns post IDs only
        'meta_query'    => array(
                                array(
                                'key'     => 'myplugin_image_id',
                                'value'   => $postid,
                                'compare' => 'LIKE' 
                                )
        )                   
    );

    $image_item_ids = get_posts( $args ); 
    foreach( $image_item_ids as $image_item_id )  {          
            $purge = wp_delete_post( $image_item_id, true ); // delete the image item, skipping trash    
    }
    wp_reset_postdata();
}  
3
  • Better by what criteria?
    – s_ha_dum
    Commented Mar 15, 2013 at 20:56
  • Performance wise.
    – urok93
    Commented Mar 15, 2013 at 21:17
  • 2
    get_posts itself just creates a new WP_Query, all parameters being equal it's exactly the same.
    – Milo
    Commented Mar 16, 2013 at 5:24

2 Answers 2

2

get_posts() simply uses a WPQuery object and sets a few default values. In general the values it sets make it mildly more performant. But I wouldn't worry to much about it.

get_posts() is simplier so as a rule of thumb if you don't need any of the more involved features of WP_Query (including pagination) - then stick with it. But largely comes down to personal preference.

I would leave your example as is. Though you don't need to explicitly set all the values as `get_posts' sets some by default.

1

If you use WP_Query and create a new object you wont touch the main query keeping it clean. Its safe to use anywhere. Its more complicated but gives you more control and power.

4
  • Actually here is a useful post wordpress.stackexchange.com/questions/1753/…
    – Jimbo
    Commented Mar 15, 2013 at 20:42
  • how would loop look if I used WP_Query (considering I am using the 'fields' => 'ids' parameter?
    – urok93
    Commented Mar 16, 2013 at 4:43
  • Something like.. $delete_images = new WP_Query($args); while($delete_images->have_posts()){ $delete_images->the_post(); wp_delete_post( get_the_ID(), true ); }
    – Jimbo
    Commented Mar 16, 2013 at 15:19
  • Actually that didn't work as the_post is not available (I believe) when using the 'fields' => 'ids' paramter.
    – urok93
    Commented Mar 16, 2013 at 16:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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