Using WordPress ‘the_title’ PHP filter

The the_title WordPress PHP filter allows you to modify the post title before it is displayed on the screen.

Usage

add_filter('the_title', 'your_custom_function', 10, 2);
function your_custom_function($post_title, $post_id) {
  // your custom code here
  return $post_title;
}

Parameters

  • $post_title string: The post title.
  • $post_id int: The post ID.

More information

See WordPress Developer Resources: the_title

Examples

Changing the title for a specific post

add_filter('the_title', 'change_specific_post_title', 10, 2);
function change_specific_post_title($post_title, $post_id) {
  if ($post_id == 42) {
    $post_title = 'Custom Title for Post 42';
  }
  return $post_title;
}

Adding a prefix to all post titles

add_filter('the_title', 'add_title_prefix', 10, 2);
function add_title_prefix($post_title, $post_id) {
  $post_title = 'Prefix - ' . $post_title;
  return $post_title;
}

Uppercasing all post titles

add_filter('the_title', 'uppercase_titles', 10, 2);
function uppercase_titles($post_title, $post_id) {
  $post_title = strtoupper($post_title);
  return $post_title;
}

Replacing a word in all post titles

add_filter('the_title', 'replace_word_in_title', 10, 2);
function replace_word_in_title($post_title, $post_id) {
  $post_title = str_replace('OldWord', 'NewWord', $post_title);
  return $post_title;
}

Hiding the title for specific post types

add_filter('the_title', 'hide_title_for_post_type', 10, 2);
function hide_title_for_post_type($post_title, $post_id) {
  $post_type = get_post_type($post_id);
  if ($post_type == 'custom_post_type') {
    $post_title = '';
  }
  return $post_title;
}