wp_document主题自动识别文章标题添加导航

wp_document主题在文章的左侧有一个“悬浮文章导航目录”,非常的实用。可以通过添加类似[h?]标签的方式来自动识别标题,但是WordPress固有的标题格式是<h?>格式的,所以不能直接识别添加导航目录。老白博客今天分享的就是将原标题<h?>转化为document主题能够识别[h?]格式,详细教程代码如下:

wp_document主题自动识别文章标题添加导航

标题转化代码

功能代码如下,添加到主题文件目录——include——config.php文件底部即可

/*docunment主题自动识别标题并添加标签 */
function update_headings() {
    $args = array(
        'post_type' => 'post', // 文章类型,可以根据需要修改
        'posts_per_page' => -1, // 获取所有文章
    );
    $posts = get_posts($args);
    foreach ($posts as $post) {
        $content = $post->post_content;
        if (strpos($content, '

') === false) { $content = preg_replace('/<h1>(.*?)</h1>/', '<h1>[h1]$1

</h1>', $content); } if (strpos($content, '

') === false) { $content = preg_replace('/<h2>(.*?)</h2>/', '<h2>[h2]$1

</h2>', $content); } if (strpos($content, '

') === false) { $content = preg_replace('/<h3>(.*?)</h3>/', '<h3>[h3]$1

</h3>', $content); } $post->post_content = $content; wp_update_post($post); } } update_headings();

类似的,老白博客还有一个“wp_document主题自动识别图片添加灯箱功能”教程,链接如下

https://www.xcbtmw.com/29463.html