Using WordPress ‘pre_{$field}’ PHP filter

The pre_{$field} WordPress PHP filter allows you to modify the value of a specific post field before it gets saved to the database.

Usage

add_filter('pre_{$field}', 'your_custom_function', 10, 1);

function your_custom_function($value) {
  // your custom code here
  return $value;
}

Parameters

  • $value (mixed): The value of the post field.

More information

See WordPress Developer Resources: pre_{$field}

Examples

Modify post title before saving

add_filter('pre_post_title', 'modify_post_title', 10, 1);

function modify_post_title($title) {
  // Add a prefix to the post title
  $title = "Modified: " . $title;
  return $title;
}

Add a suffix to the post excerpt

add_filter('pre_post_excerpt', 'add_excerpt_suffix', 10, 1);

function add_excerpt_suffix($excerpt) {
  // Add a suffix to the post excerpt
  $excerpt .= " - Read more!";
  return $excerpt;
}

Sanitize custom field value

add_filter('pre_post_meta_key', 'sanitize_custom_field', 10, 1);

function sanitize_custom_field($value) {
  // Sanitize custom field value
  $value = sanitize_text_field($value);
  return $value;
}

Convert post content to uppercase

add_filter('pre_post_content', 'uppercase_post_content', 10, 1);

function uppercase_post_content($content) {
  // Convert post content to uppercase
  $content = strtoupper($content);
  return $content;
}

Replace specific word in post title

add_filter('pre_post_title', 'replace_word_in_title', 10, 1);

function replace_word_in_title($title) {
  // Replace 'example' with 'demo' in the post title
  $title = str_replace('example', 'demo', $title);
  return $title;
}