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(); ?>
</header>
...
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).
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 usesget_the_title
, or just useget_the_title
. PHP also has runkit_function_redefine but that will require you to havePECL runkit
and php version >= 7.0the_title()
, so even if you could filter outside them you still wouldn't be outside the heading tags on many themes.