WP_Query or get_posts?

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();
}  

Solutions Collecting From Web of "WP_Query or get_posts?"

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.

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.