Tìm theo từ khóa

Cách tạo mục lục tự động cho bài viết wordpress (TOC)



Cách tạo mục lục tự động cho bài viết wordpress (TOC)

Tạo file codfe-toc.php trong thư mục theme hiện hành nhé

<?php
/**

 *
 * codfe Custom Functions
 *
 */


/**
 *  codfe 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);

CSS cho TOC vừa tạo

.codfe-auto-toc{
	padding:2rem 2rem 0.5rem 3rem;
	margin-bottom:2rem;
	background:#f5f7fa;
	border-radius: 16px;
	max-height:440px;
	overflow:auto;
}
.codfe-auto-toc .toc-list {
	margin-left: 1.1rem;
}
.codfe-auto-toc .toc-title{
	font-size:24px;
	font-weight:700;
	margin: 0 0 1rem;
}
.toc-list li:not(:last-child) {
	padding-bottom: 0.5rem;
}
.entry-content li::marker{color: #f56f46;}
.codfe-auto-toc a{
	font-size:16px;
	font-weight: 500;
}

Thêm (gọi) file vừa tạo vào trong theme đang hoạt đông bằng dòng code sau:

include_once 'codfe-toc.php';

Chúc các bạn thành công và làm tốt công việc của mình nhé!

Bài viết tham khảo nguồn

https://vietrick.com/

5/5 - (1 bình chọn)
0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Mới nhất
Cũ nhất Được bỏ phiếu nhiều nhất
0
Rất thích suy nghĩ của bạn, hãy bình luận.x