如何在帖子保存时解析帖子内容并将其保存在自定义metabox中

问题描述

我想为我的博客上的帖子生成目录,

add_filter( 'the_content','my_preg_replace_callback_function' );

但是缺点是,每次有人访问任何帖子时,代码都必须运行。

我只想在save_post钩子上运行代码,并将html目录存储在数据库中。 我认为要做方法是将其存储在自定义MetaBox字段中。 因此,我创建了一个带有文本字段的自定义MetaBox。 这些功能正常工作,因为如果我取消注释$data = $_POST['toc_field'];并将$data而不是$tableOfContents2放在update_post_Meta()内,一切将正确保存。 但是,如果我运行以下代码,则自定义MetaBox字段将填充<div class='toc'><h4>Spis treści<span class='toggle'>+</span></h4><ul class='toc-items'></ul></div>

add_action( 'save_post','mike_save_toc_data' );
function mike_save_toc_data( $post_id ) {
    if ( !isset( $_POST['mike_toc_nonce'] ) ) {
        return;
    } elseif ( !wp_verify_nonce( $_POST['mike_toc_nonce'],'mike_save_toc_data' ) ) {
        return;
    }
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
        return;
    }
    if ( !current_user_can( 'edit_post',$post_id )) {
        return;
    }
    if ( !isset($_POST['toc_field'] ) ) {
        return;
    }
    // $data = $_POST['toc_field'];
    global $post;
    $content = $post->post_content;
    $tableOfContents2 = "
        <div class='toc'>
        <h4>"
           . __( 'Spis treści','MikeTheme' ) . "<span class='toggle'>+</span>
        </h4>
        <ul class='toc-items'>";
    $index = 1;
    // Insert the IDs and create the TOC.
    // use for all headings: $content = preg_replace_callback('#<(h[1-6])(.*?)>(.*?)</\1>#si',function ($matches) use (&$index,&$tableOfContents) {
    $content = preg_replace_callback('#<(h2)(.*?)>(.*?)</\1>#si',&$tableOfContents2) {
        $tag = $matches[1];
        $title = strip_tags($matches[3]);
        $hasId = preg_match('/id=(["\'])(.*?)\1[\s>]/si',$matches[2],$matchedIds);
        $id = $hasId ? $matchedIds[2] : $index++ . '-' . sanitize_title($title);
        $tableOfContents2 .= "<li class='toc-item item-$tag'><a href='#$id'>$title</a></li>";
        if ($hasId) {
            return $matches[0];
        }
        return sprintf('<%s%s id="%s" class="anchor-offset">%s</%s>',$tag,$id,$matches[3],$tag);
    },$content);
    $tableOfContents2 .= '</ul></div>';
    update_post_Meta( $post_id,'_toc_value_key',$tableOfContents2 );
}

似乎$post->post-content;是空的,尽管我不能说,因为我不知道如何var_dump通过ajax调用在服务器上完成的工作……有人可以提出更好的解决方案吗? / p>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)