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

移除WordPress摘要中的短代码技术求助

解决WordPress摘要显示短代码的问题

问题根源

你之前尝试的add_filter('the_excerpt', 'strip_shortcodes')仅对WordPress自动生成的摘要(通过the_excerpt()调用)生效,但你是直接调用get_the_content()生成自定义摘要,这个函数不会触发the_excerpt过滤器,所以之前的方法无效。

解决方案

方案1:直接在调用处处理短代码

修改当前的调用代码,先通过strip_shortcodes()移除内容中的短代码,再进行截取:

<?php echo wp_trim_words( strip_shortcodes( get_the_content() ), 35, '...' ); ?>

如果需要更干净的纯文本摘要(移除HTML标签),可以再加一层处理:

<?php echo wp_trim_words( wp_strip_all_tags( strip_shortcodes( get_the_content() ) ), 35, '...' ); ?>

方案2:全局过滤(无需修改模板代码)

在主题的functions.php中添加以下代码,针对列表/归档/搜索页的内容自动移除短代码,不影响文章详情页:

add_filter( 'the_content', 'strip_shortcodes_for_post_list', 10 );
function strip_shortcodes_for_post_list( $content ) {
    // 判断当前是否为列表、归档或搜索页面
    if ( is_home() || is_archive() || is_search() ) {
        return strip_shortcodes( $content );
    }
    // 文章详情页返回原内容
    return $content;
}

添加后,你原来的wp_trim_words( get_the_content(), 35, '...' )调用就能自动过滤掉短代码。

方案3:封装自定义摘要函数

如果需要多次使用,建议在functions.php中封装专用函数,方便调用:

function get_custom_post_summary( $word_count = 35 ) {
    // 获取内容并移除短代码和HTML标签
    $clean_content = wp_strip_all_tags( strip_shortcodes( get_the_content() ) );
    // 截取指定字数的摘要
    return wp_trim_words( $clean_content, $word_count, '...' );
}

调用时直接使用:

<?php echo get_custom_post_summary(35); ?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 01:42:26