WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a custom script/plugin I am using for myself that creates a post along with some postmeta information. Right now, I have multiple $wpdb->insert, but I would like to condense this down into one query. How would I do this?

Here is my current code:

$meta_table = $wpdb->prefix . 'postmeta';

    $wpdb->insert( 
    $meta_table, 
    array( 
        'post_id' => $post_id, // Already defined
        'meta_key' => 'client-pwd',
        'meta_value' => $post_pwd // Already defined
        )
        );  

$wpdb->insert( 
    $meta_table, 
    array( 
        'post_id' => $post_id, 
        'meta_key' => 'gallery-status',
        'meta_value' => 'private'
        )
        );  

$wpdb->insert( 
    $meta_table, 
    array( 
        'post_id' => $post_id, 
        'meta_key' => 'meta-description',
        'meta_value' => 'Description...'
        )
        );  

$wpdb->insert( 
    $meta_table, 
    array( 
        'post_id' => $post_id, 
        'meta_key' => 'can-purchase',
        'meta_value' => 'yes'
        )
        );  

$wpdb->insert( 
    $meta_table, 
    array( 
        'post_id' => $post_id, 
        'meta_key' => 'can-email',
        'meta_value' => 'yes'
        )
        );  

$wpdb->insert( 
    $meta_table, 
    array( 
        'post_id' => $post_id, 
        'meta_key' => 'can-download',
        'meta_value' => 'yes'
        )
        );  
share|improve this question

You can't insert multiple rows via wpdb's insert, you have to do it with raw SQL:

INSERT into $meta_table (post_id, meta_key, meta_value) 
VALUES
('val1', 'val2', 'val3'),
('otherval1', 'otherval2', 'otherval3')

However-

You should always use the API where a function exists- use add_post_meta so your plugin integrates with the WordPress environment and its behavior can be modified without having to edit the plugin's files directly.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.