Home > Net >  Updating meta value for specific ids
Updating meta value for specific ids

Time:11-26

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?

CodePudding user response:

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(); }
  • Related