0

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'
        )
        );  

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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