/*
Plugin Name: Mi Plugin
Description: Un plugin NAME_1 mostrar una lista anidada de cabeceras.
Version: 1.0
Author: NAME_2
*/

function mi_plugin_register_block() {
    wp_register_script(
        'mi-plugin-script',
        plugins_url('toc.js', __FILE__),
        array('wp-blocks', 'wp-editor', 'wp-element', 'wp-data')
    );

    register_block_type('mi-plugin/listado-cabeceras', array(
        'editor_script' => 'mi-plugin-script',
        'render_callback' => 'mi_plugin_render_callback',
        'attributes' => array(
            'headings' => array(
                'type' => 'array',
                'default' => array(),
            ),
        ),
    ));
}
add_action('init', 'mi_plugin_register_block');

function add_ids_to_headings($content) {
  $pattern = '/<h([1-6])(.*?)>(.*?)<\/h[1-6]>/';
  $replacement = '<h$1$2 id="$3">$3</h$1>';

  return preg_replace_callback($pattern, function ($matches) {
      $anchor_id = sanitize_title_with_dashes($matches[3]);
      return '<h' . $matches[1] . $matches[2] . ' id="' . $anchor_id . '">' . $matches[3] . '</h' . $matches[1] . '>';
  }, $content);
}
add_filter('the_content', 'add_ids_to_headings');

function mi_plugin_render_callback($attributes) {
  global $post, $pages;
  $headings = $attributes['headings'];

  // Obtiene los enlaces permanentes NAME_3 página del post
  $page_links = array();
  for ($i = 1; $i <= count($pages); $i++) {
      $page_links[] = _wp_link_page($i);
  }

  function render_nested_headings($headings, $page_links, $pages) {
      $output = '<ul>';
      foreach ($headings as $heading) {
          $anchor_id = sanitize_title_with_dashes($heading['text']);

          // Encuentra la página que contiene la cabecera
          $page_number = 1;
          for ($i = 0; $i < count($pages); $i++) {
              if (strpos($pages[$i], 'id="' . $anchor_id . '"') !== false) {
                  $page_number = $i + 1;
                  break;
              }
          }

          // Construye el enlace correcto NAME_1 la cabecera en la lista
          $link = $page_links[$page_number - 1] . '#' . $anchor_id . '">';
          $link_end = '</a>';

          $output .= '<li><a href="' . $link . '">' . $heading['text'] . $link_end;
          if (!empty($heading['children'])) {
              $output .= render_nested_headings($heading['children'], $page_links, $pages);
          }
          $output .= '</li>';
      }
      $output .= '</ul>';
      return $output;
  }

  return render_nested_headings($headings, $page_links, $pages);
} Write your response with at least 150 words.
user