Does WordPress provide a way of rolling back when using, for example, update_post_meta or wp_insert_post?

E.g. I'm inserting a new post and giving it some post meta inside one function:


    $post_id = wp_insert_post($args, true);
    update_post_meta($post_id, 'meta_key', 'meta_value');   
}catch(Exception $e){


Or do I have to use vanilla SQL, or the $wpdb object?


  • There's no built-in function - you'll have to use $wpdb->query( "START TRANSACTION" ) etc. – TheDeadMedic Nov 23 '16 at 11:30
  • 1
    Ok, thanks. Imma look into the possibility of writing some code/a plugin that could make transactions work with the other WP functions. Maybe I'll be able to halt the execution of SQL queries inside those functions, until a 'commit' function is called. It'll be called 'Y U NO DO TRANSACTIONS, WordPress.... (with update_post_meta)'. – Dan. Nov 25 '16 at 14:40

There is no functions in wordpress to handle transactions but you can easily use the $wpdb object to make a simple query to achieve this. The following function will start a transaction and then insert a new user into the database and finally rollback the current transaction. In order to make the transaction permanent you would instead use $wpdb->query('COMMIT');

function test_transaction() {
  global $wpdb;

  // begin transaction
  $wpdb->query('START TRANSACTION');

  $user = array(
    'user_pass' =>  'sample_password',
    'user_login' => 'sample_login',
    'user_email' => 'sample@example.com',
    'first_name' => 'sample_firstname',
    'last_name' => 'sample_lastname',
  $user_id = wp_insert_user($user);

  // roll back everything - e.g remove the new user record from the database
| improve this answer | |
  • Do you need a COMMIT or is that assumed if no ROLLBACK is encountered? – HPWD Apr 6 at 0:16
  • You must use COMMIT: "if no ROLLBACK is encountered" is the halting problem. Note that in order to use transactions you have to disable 'autocommit' (active by default for mysql) otherwise every command is committed so the transaction has no reason to be started. In this case there will be an auto rollback of the last query in case of errors (e.g. integrity/uniqueness constraints violation, sql syntax errors...). – Fil Jul 2 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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