Tabla de Contenido en WordPress [Sin Plugin]

En esta publicación te enseñare cómo agregar una tabla de contenido a todas las publicaciones de tu sitio de WordPress de forma automática y sin necesidad de usar un plugin.

Para lograr esto utilizaremos un code snippet, que puedes agregar a (1) tu plugin favorito de code snippets, (2)a la carpeta mu-plugin si tienes una o (3) en el functions.php de tu child theme.

Si no deseas usar un code snippet para lograr tener una tabla de contenido en todo tus publicaciones puedes usar un TOC plugin del repositorio de WordPress

Si usas un plugin, puedes controlar el funcionamiento del plugin y posiblemente encontrarás más funcionalidades que las que un simple code snippet puede agregar.

Si deseas una ruta simple, este breve tutorial te permitirá hacerlo sin tener que recurrir a plugins.



Code Snippet: Tabla de Contenidos

Este es el código que uso para agregar una tabla de contenido a todas mis publicaciones.

Lo único que hago es crear un archivo PHP en la carpeta mu-plugin usando FileZilla o un plugin de manejo de archivos como File Manager

<?php

/*
  Plugin Name: TOC
  Plugin URI: https://wpsurfer.com
  Description: Add a Table of Content to all Posts Before the First Heading
  Version: 1.0
  Author: TicoLibre
  Author URI: https://wpsurfer.com
*/

function add_table_of_contents_before_first_heading($content) {
  // check if the current post type is "post" and if the content contains at least one heading
  if(get_post_type() == 'post' && preg_match('/<h[2-6]/', $content)) {
    // generate the table of contents
    $table_of_contents = '<div class="table-of-contents">';
    $table_of_contents .= '<h2>Tabla de Contenidos</h2>';
    $table_of_contents .= '<ul>';

    // find all headings in the content
    preg_match_all('/<h([2-6])(.*?)>(.*?)<\/h[2-6]>/', $content, $matches);
    foreach($matches[0] as $key => $heading) {
      // extract the heading level and text
      $heading_level = $matches[1][$key];
      $heading_text = $matches[3][$key];

      // add the heading to the table of contents
      $table_of_contents .= '<li><a href="#'.sanitize_title($heading_text).'">'.$heading_text.'</a></li>';

      // add an anchor to the heading
      $content = str_replace($heading, '<a id="'.sanitize_title($heading_text).'"></a>'.$heading, $content);
    }

    $table_of_contents .= '</ul>';
    $table_of_contents .= '</div>';

    // insert the table of contents before the first heading
    $content = preg_replace('/<h[2-6]/', $table_of_contents.'<h2', $content, 1);
  }

  return $content;
}
add_filter('the_content', 'add_table_of_contents_before_first_heading');

CSS para la Tabla de Contenidos

Debido a que el code snippet solo genera la tabla de contenido en cada una de las publicaciones, debemos usar un poco de CSS para darle el estilo deseado y que este no luzca como que si no tuviera alma

Este el snippet de CSS que te ayudará a darle estilo a las tablas de contenido

/*TOC*/
.table-of-contents{padding:1em;background-color:#f9f8ff;border:1px solid #ddd}.table-of-contents h2{margin-top:0;margin-bottom:.5em}.table-of-contents li{margin-bottom:.3em}.table-of-contents a{color:#333;text-decoration:none}.table-of-contents a:hover{text-decoration:underline}

Debido a que no deseo usar un plugin para agregar eso y otros estilos, agrego el CSS en el child theme de mi tema de WordPress.


Manuel Campos, English Professor

Manuel Campos

I am José Manuel. I am writing about things I know and things that I am learning about WordPress. I hope you find the content of this blog useful.

WP SURFER

home

about

privacy

contact

© 2024 WP SURFER • Made with Love in Costa Rica