Gecko Room
Gecko Room

Reputation: 29

Bulk wpdb insert for all posts [Wordpress]

I've managed to save a string into Wordpress database. The problem is that I am only able to insert the string when this code runs in a single url. I've got around 1500 posts in my database so I'd like to make it work for all of them.

global $wpdb;

$result = $wpdb->replace(
    $wpdb->postmeta,
    array(
        'post_id' => $post->ID,
        'meta_key' => 'ratingpost',
        'meta_value' => $ratingvalue
    ),
    array(
        '%s',
        '%s',
        '%s'
    )
);

I'd like to make this insert in all the posts without having to load every single url. I suppose I should do that via functions.phpbut I haven't found a proper way to do it.

Upvotes: 0

Views: 704

Answers (2)

kindisch
kindisch

Reputation: 776

Just use SQL for this:

global $wpdb;

$updated = $wpdb->query( UPDATE {$wpdb->postmeta} pm, {$wpdb->posts} p SET pm.meta_value = {$ratingvalue} WHERE pm.meta_key = 'ratingpost' AND p.ID = pm.post_id );

Upvotes: 1

Savan
Savan

Reputation: 307

Yes, you can achieve this by putting this code into functions.php , but this will insert all post every time site loads, so add this once and remove after complete execution.

<?php

 global $wpdb;
 $args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );

 $myposts = get_posts( $args );
 foreach ( $myposts as $post ) : setup_postdata( $post ); ?>

 $ratingvalue = get_post_meta($post->ID,'ratingpost',true);
 $result = $wpdb->replace(
 $wpdb->postmeta,
   array(
      'post_id' => $post->ID,
      'meta_key' => 'ratingpost',
      'meta_value' => $ratingvalue
        ),  
  array(
      '%s',
      '%s',
      '%s'
       )
   );  
 <?php endforeach; 
 wp_reset_postdata();?>

Upvotes: 2

Related Questions