I want to replace the

-tag around the_excerpt.

Right now html-output looks like this: <p> ...content of the excerpt... </p>

I want to achieve this: <h2> ...content of the excerpt... </h2>

I tried to use the following code in the content-page.php but it does not change anything.

<?php the_excerpt( '<h2>', '</h2>' ); ?>

Do you have any suggestions?

1 Answer 1


You should try this:

function replace_tag($string){
    $search = array('<p>', '</p>');
    $replace = array('<h2>', '</h2>');
    echo str_replace($search, $replace, $string);
    return $string;
add_filter('the_excerpt', 'replace_tag');

or this:

function replace_tag($string){
    $replace = array(
        '<p>' => '<h2>',
        '</p>' => '</h2>'
    $string = str_replace(array_keys($replace), $replace, $string);
    return $string;
add_filter('the_excerpt', 'replace_tag');
  • Thank you very much. The second solution worked perfectly... the first one causes the excerpt to appear twice.
    – paelzer
    Mar 8, 2020 at 11:13
  • Oh... I just saw it changes the tags in every instance the_excerpt() is used on the website. Can I limit it to be only used on a specific page template? I don't want to use it in the loop on the front page for example.
    – paelzer
    Mar 8, 2020 at 12:09
  • yes, you can use is_page_template() or get_page_template_slug to limit a specific template in an if statement
    – franz877
    Mar 8, 2020 at 14:55
  • Can you tell me how to limit the use of the filter for content-single.php, please?
    – paelzer
    Mar 8, 2020 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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