update meta_value for all posts to the same value

Essentially what I need to do is create a “default” value for a custom meta box.

the number in the meta box will be constantly changing, but in order for my code to work, I need to start with a value of 1 in the field.

I need to update this for all woocommerce products, and the meta_field is called search_priority

I started with some php as I prefer to operate outside of the sql database.

add_action('init', 'update_all_products_to_default');
function update_all_products_to_default() {
  $args = array(
    'posts_per_page'   => -1,
    'post_type' => 'product'
  $posts_array = get_posts( $args );

  foreach($posts_array as $post_array) {
    update_post_meta($post_array->ID, 'search_priority', '1');

now, I really think that this would work, but my site ( only tried on mamp so far ) kept crashing.

when I changed posts_per_page to 1000, the code ran and updated the first 1000 products on my site. great … except I have 26,000 total.

So now I am turning to SQL in attempts to enter in the value 1 for each product.

here is where i am at.

UPDATE wp_postmeta 
SET meta_value= 1 
WHERE meta_key = 'search_priority' 
AND post_id IN (SELECT ID FROM wp_posts WHERE post_type = 'product')

however this query took 20ms, and affected 0 rows.

I would really appreciate any pointers.

Thank you

Read more here: update meta_value for all posts to the same value

Leave a Reply

Your email address will not be published. Required fields are marked *