Search code examples
phpwordpresscustom-post-type

Delete Wordpress posts programmatically based on a meta field value


I want to delete WordPress post if its custom field has a certain value. "mls" is the field's id and, for example, 185897 is the value. However, if I run this script, it deletes all of my posts with given post type. I also tried 'meta_query' instead of 'meta_input', but the result is the same.

Any idea what am I missing?

$delete_post = array(
    'post_type'   => 'estate_property',
    'post_status' => 'publish',
    'meta_input'  => array(
       'mls' => 185897
    )
);

$posts = new WP_Query( $delete_post );

if ( $posts->have_posts() ) {
    while ( $posts->have_posts() ) {
        $posts->the_post();
         wp_delete_post( get_the_ID());
    }
}  

Solution

  • $delete_post = array(
        'numberposts' => -1,    // The number of posts to retrieve, otherwise 5
        'post_type'   => 'estate_property',
        'post_status' => 'publish',
        'meta_query' => array(
            array(
                'key' => 'mls',
                'value' => '185897'
            )
        )
    );
    

    or

    $delete_post = array(
        'numberposts' => -1,    // The number of posts to retrieve, otherwise 5
        'post_type'   => 'estate_property',
        'post_status' => 'publish',
        'meta_key' => 'mls',
        'meta_value' => '185897',
    );
    

    Does that work instead?