Skip to content

Instantly share code, notes, and snippets.

@vietrick
Last active September 29, 2023 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vietrick/d83cf57a80be2590694ff58874fa9fe1 to your computer and use it in GitHub Desktop.
Save vietrick/d83cf57a80be2590694ff58874fa9fe1 to your computer and use it in GitHub Desktop.
Tạo và chèn bảng mục lục Wordpress tự động
<?php
/**
*
* Vietrick Custom Functions
*
* @package Vietrick
*/
/**
* Vietrick custom TOC
*/
add_filter( 'the_content', function( $content ) {
// Adding ID slug for heading
$content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) {
if ( ! stripos( $matches[0], 'id=' ) ) :
$matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
endif;
return $matches[0];
}, $content );
//main TOC
$toc_title = "Xem nhanh";
$toc_content = "";
preg_match_all('/<(h[1-3])(?:.* id="(.*?)")?>((.*?))<\/h/',$content,$matches);
$levels = $matches[1];
$anchors = $matches[2];
$headings = $matches[3];
if ( $headings ) {
$toc_content = '<nav class="vietrick-auto-toc">';
$toc_content .= '<h3 class="toc-title">'.$toc_title.'</h3>';
if (!function_exists('collate_row')) {
function collate_row($depth, $anchor, $heading) {
$level = substr($depth, 1);
$heading = strip_tags($heading);
if ( $anchor ) {
return ["<a href='#{$anchor}' class='heading-{$depth} toc-link smooth-scroll'>{$heading}</a>", $level];
} else {
$slug = sanitize_title($heading);
return ["<a href='#{$slug}' class='heading-{$depth} toc-link smooth-scroll'>{$heading}</a>", $level];
}
}
}
$collated = array_map('collate_row', $levels, $anchors, $headings );
$previous_level = 2;
$toc_content .= '<ul class="toc-list">';
foreach ($collated as $row) {
$current_level = $row[1];
if ( $current_level == $previous_level ) {
$toc_content .= '<li>' . $row[0];
} else if ( $current_level < $previous_level ) {
$toc_content .= str_repeat('</ul>', $previous_level - $current_level) . '<li>'. $row[0];
} else {
$toc_content .= '<ul><li>' . $row[0];
}
$previous_level = $row[1];
}
$toc_content .= str_repeat('</ul>', $previous_level) . '</li></ul>';
$toc_content .= '</nav>';
}
//Add Toc before first heading
if (preg_match('/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i',$content)){
$content = preg_replace('/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i',$toc_content.'${0}',$content,1);
}else{
$content = $toc_content.$content;
}
return $content;
}, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment