Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer 1

up vote 4 down vote accepted

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 );
}
share|improve this answer
    
I learnt something today thanks to you. Wish you the best for 2013. –  Jk_ Dec 20 '12 at 23:40
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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