How do you I go about setting WordPress to a read-only state?
I have a setup that scales slaves instances with read-only database access but I’m seeing a lot of log data where WordPress still tries to write to the database.
update_{post_type}_metadata
, set_transient
, wpdb
… basically stopping anything attempting to write would be ideal. I can easily check to see if I’m on a MASTER instance vs. SLAVE instance so I could modify hooks pretty early.
Trying to short-circuit the update metadata function seems like possibly eliminating one vector, but the rest I fear involve modifying WP Core.
add_filter ( 'update_post_metadata', '__return_false', 99 );
$result = update_post_meta( -1, 'test-key', 'test-value' );
echo $result;
Any suggestions?
HyperDB looks promising as a more long-term solution.
1 Answer
WordPress doesn’t work well in read-only mode. It depends on the database for cache and other tasks.
However, there are a couple of options if you’d still like to proceed.
- Set the database user permissions to ‘READ ONLY’
- Use a function to intercept all db queries. We used this on our theme demo site to prevent db writes.
Function to use:
/**
* Whitelist "SELECT" and "SHOW FULL COLUMNS" queries.
*/
function my_readonly_filter( $query ) {
global $wpdb;
if ( preg_match( '/^\s*select|show full columns\s+/i', $query ) ) {
return $query;
}
// Return arbitrary query for everything else otherwise you get 'empty query' db errors.
return "SELECT ID from $wpdb->posts LIMIT 1;";
}
add_filter( 'query', 'my_readonly_filter' );