I'm making a plugin where I need to edit the H2 tags in the post content.

I've been at it for two days, but my php knowledge is too limited to solve the issue..

What I want to achieve is to return all <h2> tags as <h2 id="$headings_array_stripped">

What I can't seem to figure out is how to do this. I've tried combinations with foreach loops and preg_replace, str_replace and sorts.

The issue seems that the values inside the $headings_open_tag_array are all the same (<h2>) , so str_replace, for example, won't cycle through them, but only changes all <h2>'s to the first corresponding value of $headings_array_stripped:

str_replace( $headings_open_tag_array, $headingsarray_stripped, $article )

The code:

function replace_content_jump_menu() {

// Get metadata attached to the plugin
$jump_menu_check = get_post_meta( get_the_ID(), 'jump-menu', true );

// Get the content
$article = get_the_content();

// Retrieve all <h2>header</h2> tags (with content) and put them in an array
preg_match_all( '|<h2>(.*)</h2>|iU', $article, $headings_array ); 

// Strip h2 tags and make lowercase
$headings_array_stripped = preg_replace( '/\W+|[0-9]+|\<h2\>|\<\/h2\>/', '', array_map( 'strtolower', $headings_array[0] ) ); 

// Retrieve all <h2> tags from the_content and put them in an array
preg_match_all( '|<h2>|iU', $article, $headings_open_tag_array ); 

// preg_replace? str_replace? foreach()?

add_filter( 'the_content', 'replace_content_jump_menu' );

1 Answer 1


I found this article by Jeroen Sormani which solved my problem

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.