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

如何在WordPress所有文章的最后一段后自动添加短代码?

在WordPress文章末尾自动添加短代码的实现方法

核心思路

借助WordPress内置的the_content过滤器,在文章内容输出前修改内容,把短代码插入到最后一个</p>标签之后。

代码实现

将以下代码添加到子主题的functions.php文件或自定义插件中:

add_filter('the_content', 'add_shortcode_after_last_paragraph');
function add_shortcode_after_last_paragraph($content) {
    // 仅对单篇文章生效,若要包含页面,可改为is_singular(['post', 'page'])
    if (!is_singular('post')) {
        return $content;
    }
    
    // 定位最后一个</p>标签的位置
    $last_p_pos = strrpos($content, '</p>');
    if ($last_p_pos !== false) {
        // 替换并插入你的短代码,把[my_custom_shortcode]换成实际要使用的短代码
        $content = substr_replace($content, '</p>[my_custom_shortcode]', $last_p_pos, 4);
    } else {
        // 若文章无段落标签,直接在内容末尾添加短代码
        $content .= '[my_custom_shortcode]';
    }
    
    return $content;
}

关键说明

  • is_singular('post'):限制代码仅作用于单篇文章页面,根据需求可调整为包含页面、自定义文章类型等。
  • 短代码替换:把代码中的[my_custom_shortcode]替换成你实际需要插入的短代码即可。
  • 兼容性处理:如果文章内容不包含</p>标签(比如纯图片或无格式文本),代码会直接在内容末尾追加短代码,避免失效。

注意事项

  • 优先使用子主题修改functions.php,防止主题更新导致代码丢失。
  • 若短代码需要传递参数(比如当前文章ID),可在函数中通过get_the_ID()获取并拼接,例如[my_shortcode id=' . get_the_ID() . ']。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:35:19