0
votes

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());
    }
}  
1
'meta_input' should be 'meta_query' for a compound search, or simply 'meta_key' and 'meta_value'... So when you run the WP_Query, it's finding all posts that have post type 'estate_property' and post status 'publish'. See below for a solution. - Jeff Vdovjak

1 Answers

0
votes
$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?