Using WordPress ‘post_{$field}’ PHP filter

The post_{$field} WordPress PHP filter allows you to modify the value of a specific post field before it’s used or displayed.

Usage

add_filter('post_{$field}', 'your_custom_function', 10, 2);

function your_custom_function($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 filtered.

More information

See WordPress Developer Resources: post_{$field}

Examples

Change post title

Modify the post title to add a prefix.

add_filter('post_title', 'add_prefix_to_title', 10, 2);

function add_prefix_to_title($title, $post_id) {
    $prefix = 'Prefix: ';
    $new_title = $prefix . $title;
    return $new_title;
}

Make post content uppercase

Transform the post content to uppercase.

add_filter('post_content', 'make_content_uppercase', 10, 2);

function make_content_uppercase($content, $post_id) {
    return strtoupper($content);
}

Replace specific word in post excerpt

Replace a specific word in the post excerpt with another word.

add_filter('post_excerpt', 'replace_word_in_excerpt', 10, 2);

function replace_word_in_excerpt($excerpt, $post_id) {
    $search = 'old_word';
    $replace = 'new_word';
    return str_replace($search, $replace, $excerpt);
}

Add custom CSS class to post thumbnail

Add a custom CSS class to the post thumbnail’s HTML.

add_filter('post_thumbnail_html', 'add_custom_class_to_thumbnail', 10, 2);

function add_custom_class_to_thumbnail($html, $post_id) {
    $custom_class = 'my-custom-class';
    return str_replace('class="', 'class="' . $custom_class . ' ', $html);
}

Append read more link to post content

Add a “Read More” link to the end of the post content.

add_filter('post_content', 'append_read_more_link', 10, 2);

function append_read_more_link($content, $post_id) {
    $read_more_link = ' <a href="' . get_permalink($post_id) . '">Read More</a>';
    return $content . $read_more_link;
}