WordPress ‘pre_option’ PHP filter allows you to modify the value of an option before it is retrieved from the database.
Usage
To use the apply_filters()
function, add the following code to your theme’s functions.php file or a custom plugin file:
add_filter( 'pre_option', 'your_function_name', 10, 3 ); function your_function_name( $pre_option, $option, $default_value ) { // Your code here }
Parameters
- $pre_option (mixed): The value to return instead of the option value. Default is
false
(to skip past the short-circuit). - $option (string): Name of the option.
- $default_value (mixed): The fallback value to return if the option does not exist. Default is
false
.
Examples
Set a default site title
add_filter( 'pre_option', 'set_default_site_title', 10, 3 ); function set_default_site_title( $pre_option, $option, $default_value ) { if ( $option == 'blogname' && empty( $pre_option ) ) { return 'My Default Site Title'; } return $pre_option; }
This code sets a default site title, “My Default Site Title”, if the ‘blogname’ option is empty.
Enable maintenance mode
add_filter( 'pre_option', 'enable_maintenance_mode', 10, 3 ); function enable_maintenance_mode( $pre_option, $option, $default_value ) { if ( $option == 'maintenance_mode' ) { return true; } return $pre_option; }
This code enables maintenance mode by setting the ‘maintenance_mode’ option to true
.
Set a default timezone
add_filter( 'pre_option', 'set_default_timezone', 10, 3 ); function set_default_timezone( $pre_option, $option, $default_value ) { if ( $option == 'timezone_string' && empty( $pre_option ) ) { return 'America/New_York'; } return $pre_option; }
This code sets a default timezone, “America/New_York”, if the ‘timezone_string’ option is empty.
Set default image sizes
add_filter( 'pre_option', 'set_default_image_sizes', 10, 3 ); function set_default_image_sizes( $pre_option, $option, $default_value ) { switch ( $option ) { case 'thumbnail_size_w': return 150; case 'thumbnail_size_h': return 150; case 'medium_size_w': return 300; case 'medium_size_h': return 300; case 'large_size_w': return 1024; case 'large_size_h': return 1024; default: return $pre_option; } }
This code sets default image sizes for thumbnail, medium, and large images if their corresponding options are not set.
Limit number of posts per page
add_filter( 'pre_option', 'limit_posts_per_page', 10, 3 ); function limit_posts_per_page( $pre_option, $option, $default_value ) { if ( $option == 'posts_per_page' ) { return 5; } return $pre_option; }
This code limits the number of posts displayed per page to 5 by setting the ‘posts_per_page’ option to 5.