How to Use Transactions with wpdb in a WordPress Plugin

Posted on 20th June 2023

The WordPress wpdb class is used for interacting with a WordPress database. It’s a great tool for developers as it provides a clean and easy way to run queries and update data.

One feature of wpdb that is often overlooked is its ability to run database queries within a transaction. Transactions are a way of grouping multiple database queries together so that they all either succeed or fail as a single unit.

This can be useful in a WordPress plugin when you need to update multiple pieces of data at the same time. If any of the queries within the transaction fail, the entire transaction will be rolled back and none of the data will be updated.

In this article, we’ll show you how to use transactions with wpdb in a WordPress plugin.

What is a WordPress Transaction?

A database transaction is a group of database queries that are all executed together as a single unit.

If any of the queries within the transaction fail, the entire transaction will be rolled back and none of the data will be updated.

This is useful in a WordPress plugin when you need to update multiple pieces of data at the same time. If any of the queries within the transaction fail, the entire transaction will be rolled back and none of the data will be updated.

How to Start a WordPress Transaction

Starting a transaction is easy with wpdb. You just need to call the start_transaction() method.

Here’s an example:

$wpdb->start_transaction();

// Run your database queries here

$wpdb->commit();

In the code above, we’ve started a transaction and then run our database queries.

Once we’ve finished running our queries, we call the commit() method to commit the transaction. This will update the database with the data from our queries.

If we don’t call the commit() method, the transaction will be rolled back and none of the data will be updated.

How to Rollback a WordPress Transaction

If you need to rollback a transaction, you can call the rollback() method.

Here’s an example:

$wpdb->start_transaction();

// Run your database queries here

$wpdb->rollback();

In the code above, we’ve started a transaction and then run our database queries.

Once we’ve finished running our queries, we call the rollback() method to rollback the transaction. This will undo any changes that were made by our database queries.

How to Check if a WordPress Transaction is Running

If you need to check if a transaction is currently running, you can call the in_transaction() method.

This method will return true if a transaction is running and false if not.

Here’s an example:

if ( $wpdb->in_transaction() ) {

// A transaction is running

} else {

// A transaction is not running

}

In the code above, we’ve checked if a transaction is running. If a transaction is running, we run our database queries. If not, we rollback the transaction.

How to Use Transactions with wpdb in a WordPress Plugin

Now that we’ve covered the basics of using transactions with wpdb, let’s see how we can use them in a WordPress plugin.

We’ll start by creating a new plugin called “Plugin Transactions”.

In the plugin, we’ll create a custom post type called “Books”. We’ll also create a custom taxonomy called “Genres” to categorize our books.

Once our custom post type and taxonomy are created, we’ll need to run some database queries to populate our data.

We’ll use a transaction so that if any of the database queries fail, the entire transaction will be rolled back and none of the data will be updated.

Here’s the code for our plugin:

‘Books’,
‘singular_name’ => ‘Book’,
‘add_new’ => ‘Add New Book’,
‘add_new_item’ => ‘Add New Book’,
‘edit_item’ => ‘Edit Book’,
‘new_item’ => ‘New Book’,
‘all_items’ => ‘All Books’,
‘view_item’ => ‘View Book’,
‘search_items’ => ‘Search Books’,
‘not_found’ => ‘No books found’,
‘not_found_in_trash’ => ‘No books found in Trash’,
‘parent_item_colon’ => ”,
‘menu_name’ => ‘Books’,
);

$args = array(
‘labels’ => $labels,
‘public’ => true,
‘publicly_queryable’ => true,
‘show_ui’ => true,
‘show_in_menu’ => true,
‘query_var’ => true,
‘rewrite’ => array( ‘slug’ => ‘book’ ),
‘capability_type’ => ‘post’,
‘has_archive’ => true,
‘hierarchical’ => false,
‘menu_position’ => null,
‘supports’ => array( ‘title’, ‘editor’, ‘author’, ‘thumbnail’, ‘excerpt’, ‘comments’ )
);

register_post_type( ‘book’, $args );
}
add_action( ‘init’, ‘pw_register_book_post_type’ );

// Register custom taxonomy
function pw_register_genre_taxonomy() {

$labels = array(
‘name’ => ‘Genres’,
‘singular_name’ => ‘Genre’,
‘search_items’ => ‘Search Genres’,
‘all_items’ => ‘All Genres’,
‘parent_item’ => ‘Parent Genre’,
‘parent_item_colon’ => ‘Parent Genre:’,
‘edit_item’ => ‘Edit Genre’,
‘update_item’ => ‘Update Genre’,
‘add_new_item’ => ‘Add New Genre’,
‘new_item_name’ => ‘New Genre Name’,
‘menu_name’ => ‘Genres’,
);

register_taxonomy( ‘genre’, array( ‘book’ ), array(
‘hierarchical’ => true,
‘labels’ => $labels,
‘show_ui’ => true,
‘query_var’ => true,
‘rewrite’ => array( ‘slug’ => ‘genre’ ),
) );
}
add_action( ‘init’, ‘pw_register_genre_taxonomy’ );

// Populate data
function pw_populate_data() {

// Insert books
$books = array(
array(
‘title’ => ‘The Hobbit’,
‘author’ => ‘J.R.R. Tolkien’,
‘genre’ => ‘Fantasy’
),
array(
‘title’ => ‘The Hunger Games’,
‘author’ => ‘Suzanne Collins’,
‘genre’ => ‘Dystopian’
),
array(
‘title’ => ‘To Kill a Mockingbird’,
‘author’ => ‘Harper Lee’,
‘genre’ => ‘Historical’
)
);

// Start transaction
global $wpdb;
$wpdb->start_transaction();

foreach ( $books as $book ) {

// Insert book
$wpdb->insert(
‘wp_posts’,
array(
‘post_title’ => $book[‘title’],
‘post_content’ => ”,
‘post_status’ => ‘publish’,
‘post_author’ => 1,
‘post_type’ => ‘book’
)
);

// Get book ID
$book_id = $wpdb->insert_id;

// Insert book author
$wpdb->insert(
‘wp_posts’,
array(
‘post_title’ => $book[‘author’],
‘post_content’ => ”,
‘post_status’ => ‘publish’,
‘post_author’ => 1,
‘post_parent’ => $book_id,
‘post_type’ => ‘book_author’
)
);

// Get author ID
$author_id = $wpdb->insert_id;

// Set book author
$wpdb->update(
‘wp_posts’,
array(

When you’re done, save your changes and close the file.

Now that you know how to use transactions with wpdb in a WordPress plugin, you can start developing more complex plugins that require database interactions. Just remember to always wrap your database code in a transaction so that you can ensure that your data is always consistent.