Add Incrementing ID to each paragraph in the_content

If I understand your question correctly, you can try the following:

add_filter( 'the_content', 'incrementparagraphs', 10, 1 );

function incrementparagraphs( $content ) 
{
     return preg_replace_callback(
         '|<p>|',
         function ( $matches )
         {
             static $i = 0;
             return sprintf( '<p data-section-id="%d">', $i++ );
         },
         $content
     );
}

to replace every <p> tags with <p data-section-id="1">, where the data-section-id attribute contains the incremental count of the current p tag.

Example:

Before:

<p>aaa</p>
<p>bbb</p>
<p>ccc</p>

After:

<p data-section-id="0">aaa</p>
<p data-section-id="1">bbb</p>
<p data-section-id="2">ccc</p>

More on preg_replace_callback here.

Leave a Comment