Using WordPress ‘pre_post_{$field}’ PHP filter

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

Usage

add_filter('pre_post_{$field}', 'my_custom_pre_post_field_filter', 10, 2);
function my_custom_pre_post_field_filter($value, $post_id) {
    // your custom code here
    return $value;
}

Parameters

  • $value (mixed) – The value of the post field.
  • $post_id (int) – The ID of the post being modified.

More information

See WordPress Developer Resources: pre_post_{$field}

Examples

Modify the post title

In this example, we will prepend “My Prefix: ” to the post title before saving it.

add_filter('pre_post_title', 'my_custom_pre_post_title_filter', 10, 2);
function my_custom_pre_post_title_filter($title, $post_id) {
    $title = "My Prefix: " . $title;
    return $title;
}

Sanitize the post content

In this example, we will remove any HTML tags from the post content.

add_filter('pre_post_content', 'my_custom_pre_post_content_filter', 10, 2);
function my_custom_pre_post_content_filter($content, $post_id) {
    $content = strip_tags($content);
    return $content;
}

Set a default value for the post excerpt

In this example, we will set a default value for the post excerpt if it is empty.

add_filter('pre_post_excerpt', 'my_custom_pre_post_excerpt_filter', 10, 2);
function my_custom_pre_post_excerpt_filter($excerpt, $post_id) {
    if (empty($excerpt)) {
        $excerpt = 'This is the default excerpt.';
    }
    return $excerpt;
}

Modify the post status

In this example, we will change the post status to “draft” if the post title contains the word “Draft”.

add_filter('pre_post_status', 'my_custom_pre_post_status_filter', 10, 2);
function my_custom_pre_post_status_filter($status, $post_id) {
    $post_title = get_post_field('post_title', $post_id);
    if (strpos($post_title, 'Draft') !== false) {
        $status = 'draft';
    }
    return $status;
}

Modify the post author

In this example, we will change the post author to a specific user with ID 5 if the post title starts with “Guest:”.

add_filter('pre_post_author', 'my_custom_pre_post_author_filter', 10, 2);
function my_custom_pre_post_author_filter($author, $post_id) {
    $post_title = get_post_field('post_title', $post_id);
    if (substr($post_title, 0, 6) === 'Guest:') {
        $author = 5;
    }
    return $author;
}