0

I'm looking for a clean way of filtering the_content to add a piece of code before each H1 tag present in it. In fact, I have a long privacy policy text and I want to add a back to the top link before each paragraph. Of course, I could easily add these in the content editor but I don't want my customer to be able to remove it accidentally.

So I have something like :

<h1>BLA BLA BLA</h1>
<p>A very interesting piece of text here...<p>
<h1>BLA BLA BLA</h1>
<p>A very interesting piece of text here...<p>
<h1>BLA BLA BLA</h1>
<p>A very interesting piece of text here...<p>

and I want to filter it to get :

<a href="#">Back to the top</a>
<h1>BLA BLA BLA</h1>
<p>A very interesting piece of text here...<p>
<a href="#">Back to the top</a>
<h1>BLA BLA BLA</h1>
<p>A very interesting piece of text here...<p>
<a href="#">Back to the top</a>
<h1>BLA BLA BLA</h1>
<p>A very interesting piece of text here...<p>

Thanks in advance for your time.

Cheers,

J.

1 Answer 1

4

Just filter 'the_content', test if you are on the correct page, then run str_ireplace():

add_filter( 'the_content', 'wpse_76808_filter_h1' );

function wpse_76808_filter_h1( $content )
{
    // page slug
    if ( ! is_page( 'privacy-policy' ) )
        return $content;

    return str_ireplace( '<h1', '<a href="#">Back to the top</a><h1', $content );
}
1
  • I learnt something today thanks to you. Wish you the best for 2013.
    – Nypam
    Dec 20, 2012 at 23:40

Your Answer

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

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