You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过子主题functions.php在父主题mega-menu.php中插入代码添加摘要

结论

可以实现,无需修改父主题原文件,直接在子主题的functions.php中添加代码片段即可,以下提供3种不同实现方案,可根据你的主题实际情况选择:


方案1:挂载主题自带钩子(最优解,性能最高)

先检查父主题/inc/mega-menu.php中the_title代码行下方是否有预留的动作钩子(通常是do_action( '钩子名' )格式),如果存在类似csco_mega_menu_after_title的专属钩子,直接使用以下代码即可:

add_action( 'csco_mega_menu_after_title', 'custom_add_mega_menu_excerpt' );
function custom_add_mega_menu_excerpt() {
    ?>
    <p class="cs-entry__excerpt">
        <?php the_excerpt(); ?>
    </p>
    <?php
}

方案2:用the_title过滤器附加内容(次优解,实现简单)

通过过滤器在标题输出后拼接摘要内容,增加判断条件避免影响全站其他位置的标题输出:

add_filter( 'the_title', 'custom_append_excerpt_to_mega_menu_title', 10, 2 );
function custom_append_excerpt_to_mega_menu_title( $title, $post_id ) {
    // 仅在前端巨幕菜单的循环输出场景生效
    if ( ! is_admin() && in_the_loop() && ! is_singular() && ! is_archive() ) {
        // 验证当前输出属于巨幕菜单的文章项,可根据主题实际逻辑调整判断条件
        global $post;
        if ( isset( $post->post_type ) && $post->post_type !== 'nav_menu_item' ) {
            ob_start();
            ?>
            <p class="cs-entry__excerpt">
                <?php echo wp_trim_words( get_the_excerpt( $post_id ), 15 ); //可自行调整摘要字数 ?>
            </p>
            <?php
            $title .= ob_get_clean();
        }
    }
    return $title;
}

方案3:输出缓冲替换(兼容性最强,无需适配主题内部逻辑)

如果前两种方案都不生效,直接捕获页面输出内容,匹配对应HTML结构后插入摘要代码:

add_action( 'template_redirect', 'custom_modify_mega_menu_output' );
function custom_modify_mega_menu_output() {
    if ( is_admin() ) return;
    // 开启输出缓冲
    ob_start( function( $html ) {
        // 匹配巨幕菜单的标题结束标签,在其后插入摘要
        $pattern = '/(<\/h6>)(\s*<div class="cs-entry__meta")/i';
        $excerpt = '<p class="cs-entry__excerpt">' . wp_kses_post( get_the_excerpt() ) . '</p>';
        return preg_replace( $pattern, '$1' . $excerpt . '$2', $html );
    } );
}

注意事项

  • 所有代码添加到子主题functions.php文件末尾即可,添加前建议先备份站点
  • 如果方案3匹配失效,可以打开前台页面查看巨幕菜单渲染后的实际HTML结构,调整正则匹配规则即可

内容的提问来源于stack exchange,提问作者nilssonc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 10:39:01