0

Delete a custom field in mysql for all posts with specific category id

I am trying to delete all custom fields with the key 'key1' from posts that are in category id '66'.

I can delete all custom fields with the key 'key1' with the following mysql query: DELETE FROM wp_postmeta WHERE meta_key = 'key1'

How do I specify the category in that query?

1 Answer 1

0

Please try with below code :

$pro_args = [];
$pro_args['post_type'] = 'post';  //Replace your post type
$pro_args['post_status'] = 'publish';
$pro_args['posts_per_page'] = -1;
$pro_args['tax_query'] = array(
    array(
      'taxonomy' => 'category', //Replace your taxonomy name
      'field' => 'id',
      'terms' => array( 66 ),
    )
);

// Optional
$pro_args['meta_query'] = array(
    'relation' => 'AND',
    array(
        'key'     => 'key1',
        'compare' => 'EXISTS',
    )
);

$pro_query  = new WP_Query( $pro_args );

if ( $pro_query->have_posts() ) {

    while ( $pro_query->have_posts() ) { $pro_query->the_post();

        delete_post_meta( get_the_ID(), 'key1' );

    }

}

wp_reset_postdata();

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.