-1

I am updating post meta with this

update_post_meta( '3100', 'mymetakey', 'mymetavalue' );

How can I add this metakey and metavalue not only to post ID 3100, but several other IDs?

grolli
  • 105
  • 1
  • 9

1 Answers1

1

You can define array of post ids and then you can iterate loop of ids. Try the below code.

$postIds = array( 3100, 1234, 5678....);

foreach ( $postIds as $key => $post_id ) {
    update_post_meta( $post_id, 'mymetakey', 'mymetavalue' );
}

Update as per OP comment.

$args = array(
    'post_type'      => 'product',
    'posts_per_page' => -1,
    'tax_query'      => array(
        array(
            'taxonomy' => 'product_cat', // custom taxonomy
            'field'    => 'slug',
            'terms'    => 'your-category-slug', // taxonomy term (category)
        )
    )
);

$products = new WP_Query( $args );

if( $products->have_have() ){ while ( $products->have_have() ) { $products->the_post();
    
    update_post_meta( get_the_ID(), 'mymetakey', 'mymetavalue' );
    
} wp_reset_postdata(); }
Bhautik
  • 11,125
  • 3
  • 16
  • 38
  • awesome. Is there also a way to check - instead of using the ids - if the post ( in my case product) belongs to a specific product category? So if product bellongs to product category A, update meta? – grolli Nov 26 '21 at 09:34
  • Do you mean retrieve products from a specific category? – Bhautik Nov 26 '21 at 09:37
  • yes. if the product belongs to product category A, all products from that category should receive the meta. All others not. – grolli Nov 26 '21 at 11:21
  • hmm..that unfortunately does not work. I have a serialised meta value, so I added $data = maybe_unserialize( 'a:1:{s:19:"order_list";a:1:{i:0;s:1:"1";}}' ); and used that in the update post meta, but it is not working... – grolli Nov 26 '21 at 16:09