Using WordPress ‘pre_set_theme_mod_{$name}’ PHP filter

The pre_set_theme_mod_{$name} WordPress PHP filter allows you to modify a theme’s options, or ‘theme_mod’, value before it is saved. The dynamic portion of the hook name, $name, refers to the key name of the modification array, such as ‘header_textcolor’, ‘header_image’, and so on.

Usage

add_filter( 'pre_set_theme_mod_{$name}', 'my_custom_function', 10, 2 );

function my_custom_function( $value, $old_value ) {
  // Your custom code here
  return $value;
}

Parameters

  • $value (mixed): The new value of the theme modification.
  • $old_value (mixed): The current value of the theme modification.

More information

See WordPress Developer Resources: pre_set_theme_mod_{$name}

Examples

Change header text color

Modify the header text color before it is saved:

add_filter( 'pre_set_theme_mod_header_textcolor', 'change_header_textcolor', 10, 2 );

function change_header_textcolor( $value, $old_value ) {
  $value = '#ff0000'; // Set the new header text color to red
  return $value;
}

Modify header image URL

Add a custom watermark to the header image URL:

add_filter( 'pre_set_theme_mod_header_image', 'add_watermark_to_header_image', 10, 2 );

function add_watermark_to_header_image( $value, $old_value ) {
  $value = $value . '?watermark=custom'; // Add a custom watermark to the header image URL
  return $value;
}

Limit custom logo size

Ensure the custom logo size does not exceed a certain dimension:

add_filter( 'pre_set_theme_mod_custom_logo', 'limit_custom_logo_size', 10, 2 );

function limit_custom_logo_size( $value, $old_value ) {
  // Check if the custom logo size exceeds 200x200 pixels
  if ( $value['width'] > 200 || $value['height'] > 200 ) {
    $value = $old_value; // Revert to the previous value if the size exceeds the limit
  }
  return $value;
}

Force a fixed background color

Set a fixed background color for the theme:

add_filter( 'pre_set_theme_mod_background_color', 'set_fixed_background_color', 10, 2 );

function set_fixed_background_color( $value, $old_value ) {
  $value = '#ffffff'; // Set the fixed background color to white
  return $value;
}

Modify site title

Append a custom text to the site title:

add_filter( 'pre_set_theme_mod_blogname', 'append_text_to_site_title', 10, 2 );

function append_text_to_site_title( $value, $old_value ) {
  $value = $value . ' - Custom Text'; // Append custom text to the site title
  return $value;
}