【发布时间】:2020-05-01 05:38:20
【问题描述】:
我找到了两种解决方案来替换 WordPress 页面中的文本。两者都“几乎”正常工作,除了一些问题:
解决方案 1:
function callback($buffer) {
// modify buffer here, and then return the updated code
return $buffer;
}
function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }
add_action('wp_head', 'buffer_start');
add_action('wp_footer', 'buffer_end');
取自:
WordPress filter to modify final html output 和
http://www.dagondesign.com/articles/wordpress-hook-for-entire-page-using-output-buffering/
它工作正常,但不允许更改页面标题。有什么办法可以改变上述方法中的页面标题?
我从一个流行的插件(代码行号 270)得到的第二个解决方案:https://wordpress.org/plugins/real-time-find-and-replace/
function far_template_redirect() {
ob_start();
ob_start( 'far_ob_call' );
//ob_end_flush(); fails here. I don't know why?
}
//Handles find and replace for public pages
add_action( 'template_redirect', 'far_template_redirect' );
它工作正常,但许多在线链接建议使用add_filter 'template_include' 而不是add_action 'template_redirect'。见:
https://markjaquith.wordpress.com/2014/02/19/template_redirect-is-not-for-loading-templates/ https://bbpress.trac.wordpress.org/ticket/1524
但如果我尝试使用add_action 'template_redirect' 而不是add_filter 'template_include',文本替换代码在某些网站上有效并破坏了其他一些网站。
人们建议ob_end_flush() 必须与ob_start() 一起使用,但是如果我在ob_start 之后的代码中包含ob_end_flush,则代码会失败。
我喜欢solution 1,但有没有办法在其中包含页眉和页脚?否则Solution 2 适用于所有网站,除了它没有ob_end_flush 并且不被很多人推荐,尽管一个流行的插件使用它。
【问题讨论】: