Custom ez-toc-settings[position]
-
Hello,
I would like to insert the ez-toc right before the second h2 tag of the posts automatically (not possible with the custom option of ez-toc-settings[position]).
I use to use Table of Contents Plus (and I want to migrate to Easy Table of Contents), and the code below used to work without any issue but when I replace the shortcode toc by ez-toc it triggers error 500 :
<?php
function insert_shortcode_before_second_h2($content) {
// Check if the post is not a page or any other custom type
if (is_singular('post')) {
// Check if the post doesn't contain [no_toc]
if (strpos($content, '[no_toc]') === false) {
// Find the second occurrence of <h2> tag
$second_h2_position = strpos($content, '<h2', strpos($content, '<h2') + 1);
// Find the opening <h2> tag after the second <h2> tag
$opening_h2_tag_position = strpos($content, '<h2', $second_h2_position);
// Insert the [toc] shortcode before the opening <h2> tag
$content = substr_replace($content, '[toc]', $opening_h2_tag_position, 0);
}
}
return $content;
}
add_filter('the_content', 'insert_shortcode_before_second_h2', 9);As a non-dev, I tried to find a solution with Claude/GPT to work on a code to do this insertion but nothing seems to be working : either the shortcode is not executed (just displayed) or the code triggers a error 500 memory limit (although i ticked the box on the admin page regarding that matter).
Below is the last version that still doesn’t work.. but maybe someone sees something obvious that could fix that ? Maybe it’s useful for others. (I’m not using any website builders)
<?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
function add_toc_before_second_h2($content) {
// Only proceed if we're on a single post
if (!is_single()) {
return $content;
}
// Find position of first h2
$pos1 = stripos($content, '<h2 class="wp-block-heading"');
if ($pos1 === false) {
return $content;
}
// Find position of second h2
$pos2 = stripos($content, '<h2 class="wp-block-heading"', $pos1 + 1);
if ($pos2 === false) {
return $content;
}
// Build new content
$content = substr($content, 0, $pos2) . '[ez-toc]' . substr($content, $pos2);
return $content;
}
// Add our function to WordPress content filter
add_filter('the_content', 'add_toc_before_second_h2', 5);Thanks a lot.
- You must be logged in to reply to this topic.