I want to display a custom HTML snippet after a page or post title.

Any theme which follows the WP guidelines will output the post or page title using the_title(). For example, the TwentyTwentyOne WP theme does it as follows:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

    <header class="entry-header alignwide">
        <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
        <?php twenty_twenty_one_post_thumbnail(); ?>


So, my first attempt has been to use the_title filter.

function filter_the_title( $title ) {
    return $title . '<h2>Whatever</h2>';
add_filter( 'the_title', 'My\Namespace\filter_the_title' );

But this does filter the title text itself, not the whole output, so my custom HTML will be inside the <h1> tag.

How may I add custom content after the_title() output, without touching the theme files (should work as a plugin for any standard WP theme).

  • 1
    the_title only has a filter for the content and not the complete structure, kind of annoying I agree. You could create your own function that uses get_the_title, or just use get_the_title. PHP also has runkit_function_redefine but that will require you to have PECL runkit and php version >= 7.0 Aug 12 '21 at 6:39
  • @Buttered_Toast Thanks for this interesting information. Aug 12 '21 at 7:44
  • 1
    Themes don't necessarily always use the arguments for the_title(), so even if you could filter outside them you still wouldn't be outside the heading tags on many themes. Aug 12 '21 at 7:52

You need to introduce your own hook (that's how I'd do it). I've added a custom hook in the following snippet:

<header class="entry-header alignwide">
    <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
    <?php do_action('custom_after_title_hook'); ?>
    <?php twenty_twenty_one_post_thumbnail(); ?>

In order for this to work, you need to have:

  1. Access to the header.php
  2. OR overwrite it in a child-theme.

Last thing is easy: just call the function in your functions.php file like this:


    function custom_after_title_hook(){

         $some_var = '<span>some text after title</span>';

         return $some_var;
    add_action('my_custom_action', 'custom_after_title_hook');


You can also add this to a plugin, but then you need to work with 'template_include'.

  • Thanks for the detailed answer, but I cannot touch the theme files nor create a child theme, since this is expected to work for any theme via a plugin. Aug 12 '21 at 7:26
  • the_title() function uses get_the_title() function, where your filter fires. Result of your filter will be wraped with h1 tags after, that's why you get h2 tags inside h1 tag.
    – anton
    Aug 12 '21 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.