Last active
October 19, 2018 12:01
-
-
Save vishalkakadiya/f79d6777797dd5c1902f367d079bb430 to your computer and use it in GitHub Desktop.
WordPress - Check for autoload options, if it's more than 1 MB then it will show admin notice in Admin area - Not for VIP environment.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Plugin Name: All Options Limit for WordPress | |
| * Description: Provides warnings and notifications for wp_options exceeding limits. | |
| * Author: Vishal | |
| * License: GPL version 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html | |
| */ | |
| /** | |
| * Inspired by VIP Go MU plugins. | |
| * Ref: https://raw.githubusercontent.com/Automattic/vip-go-mu-plugins/master/alloptions-limit.php | |
| */ | |
| function vk_get_auto_load_options_size() { | |
| $options_size = wp_cache_get( 'rt_all_autoload_options_size', 'rt_all_options_cache' ); | |
| // Cache miss | |
| if ( false === $options_size ) { | |
| $options = wp_load_alloptions(); | |
| // Strlen returns bytes. | |
| $options_size = strlen( maybe_serialize( $options ) ); | |
| wp_cache_set( 'rt_all_autoload_options_size', $options_size, 'rt_all_options_cache', 30 * MINUTE_IN_SECONDS ); | |
| } | |
| return $options_size; | |
| } | |
| function vk_convert_to_readable_size( $size ) { | |
| $base = log( $size ) / log( 1000 ); | |
| $suffix = array( '', ' KB', ' MB', ' GB', ' TB' ); | |
| $f_base = floor( $base ); | |
| return round( pow( 1000, $base - floor( $base ) ), 1 ) . $suffix[ $f_base ]; | |
| } | |
| function rt_give_admin_notice() { | |
| if ( defined( 'WP_CLI' ) && WP_CLI ) { | |
| return; | |
| } | |
| $options_size = vk_get_auto_load_options_size(); | |
| // If it's over the warning threshold notify. | |
| if ( $options_size > 1000000 ) { // 1000000 bytes ~ 1MB, too big for cache. | |
| $readable_size = vk_convert_to_readable_size( $options_size ); | |
| // NOTE - This function has built-in rate limiting so it's ok to call on every request. | |
| ?> | |
| <div class="notice notice-error is-dismissible"> | |
| <h3><?php esc_html_e( 'Too big options table!', 'rt-limit-options' ); ?></h3> | |
| <p> | |
| <?php | |
| // translators: Autoload options size. | |
| printf( esc_html__( 'Your database\'s autoload options size(%s) is exceeds than 1 MB.', 'rt-limit-options' ), esc_html( $readable_size ) ); | |
| ?> | |
| </p> | |
| </div> | |
| <?php | |
| } | |
| } | |
| add_action( 'admin_notices', 'rt_give_admin_notice', 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment