Transaction when using WP functions rather than vanilla SQL?

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' => '[email protected]',
    '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
  $wpdb->query('ROLLBACK');
};

Leave a Comment