首页 > 解决方案 > wordpress 在将文本显示给浏览器之前替换文本

问题描述

我的网站是使用默认主题构建ElementorGeneratePress,我想用数据库中的一些值替换输出的最终文本。这个插件
Real-Time Find and Replace https://wordpress.org/plugins/real-time-find-and-replace/完美地完成了替换功能,它使用了动作:

//Handles find and replace for public pages
add_action( 'template_redirect', 'far_template_redirect' );

使用代码替换文本:

function far_ob_call( $buffer ) { // $buffer contains entire page

    $far_settings = get_option( 'far_plugin_settings' );
    if ( is_array( $far_settings['farfind'] ) ) {
        foreach ( $far_settings['farfind'] as $key => $find ) {
            if( isset( $far_settings['farregex'][$key] ) ) {
                $buffer = preg_replace( $find, $far_settings['farreplace'][$key], $buffer );
            } else {            
                $buffer = str_replace( $find, $far_settings['farreplace'][$key], $buffer );
            }
        }
    }
    return $buffer;
}

我不能直接使用该插件,因为它用文本替换文本,我需要从数据库中获取数据,所以我必须制作自己的插件。但是,我发现了这个博客:https ://markjaquith.wordpress.com/2014/02/19/template_redirect-is-not-for-loading-templates/告诉我使用过滤器:

add_filter( 'template_include', 'my_callback' );

而不是插件中的上述操作:

add_action( 'template_redirect', 'far_template_redirect' );

但是插件正在使用该操作。

用什么?

插件描述说:"Set up find and replace rules that are executed AFTER a page is generated by WordPress, but BEFORE it is sent to a user's browser."这正是我想要的。即在页面生成后和页面发送到浏览器之前替换文本,但插件action用于此,其他博客建议使用filter

标签: wordpress

解决方案


推荐阅读