I need to loop through each paragraph in the_content and add an ID to each paragraph with an incremental value.
function incrementparagraphs( $content ) {
for ($i = 0; $i <count($content); $i++) {
return str_replace( "<p>", "<p data-section-id=" . $i . ">", $content );
}
}
add_filter( 'the_content', 'incrementparagraphs', 10, 1 );
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.