我正在尝试创建一个函数,在保存(the_content)时对帖子内容进行文本替换.
存根函数如下所示,但是如何获取对帖子内容的引用,然后将过滤后的内容返回到"publish_post"例程?
但是,我的替换是不工作和/或没有将更新的post_content传递给发布功能.价值永远不会被取代.
function my_function() {
global $post;
$the_content = $post->post_content;
$text = " test ";
$post->post_content = str_ireplace($text, '<b>'.$text.'</b>', $the_content );
return $post->post_content;
}
add_action('publish_post', 'my_function');
Run Code Online (Sandbox Code Playgroud)
当你提到时the_content
,你是在引用模板标签还是过滤器钩子?
the_content
作为过滤器钩子只适用于数据库读取期间的帖子内容,而不是写入.在将内容保存到数据库之前修改帖子内容时使用的过滤器是content_save_pre
.
代码示例
在你的插件或主题的functions.php中,添加你的函数,$content
用作参数.以您希望的方式修改内容,并确保返回$content
.
然后使用add_filter('filter_name', 'function_name')
在WordPress中遇到过滤器挂钩时运行该函数.
function add_myself($content){
return $content." myself";
}
add_filter('content_save_pre','add_myself');
Run Code Online (Sandbox Code Playgroud)
如果我写的帖子包括:
"到帖子的末尾,我想添加"
当保存到数据库并显示在网站上时,它将显示:
"到帖子的末尾,我想加上自己".
您的示例过滤器可能会修改为如下所示:
function my_function($content) {
$text = " test ";
return str_ireplace($text, '<b>'.$text.'</b>', $content );
}
add_filter('content_save_pre','my_function');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4795 次 |
最近记录: |