0

我正在为 wordpress 编写一个简单的插件,它可以更改页面或帖子上的单个单词以使其变为粗体。

例如:vlbs -> vlbs

它适用于普通的 Wordpress 页面和使用此代码的帖子:

defined('ABSPATH') or die('You can\'t enter this site');

class VLBS {

    function __construct() {

    }

    function activate() {
        flush_rewrite_rules();
    }

    function deactivate() {
        flush_rewrite_rules();
    }

    function unstinstall() {
    }

function new_content($content) {
                return $content = str_replace('vlbs','<strong style="color:#00a500">vlbs</strong>', $content);    
}

}

if(class_exists('VLBS')){
    $VLBS = new VLBS();

}

add_filter('the_content', array($VLBS, 'new_content'));

//activation
register_activation_hook(__FILE__, array($VLBS, 'activate'));

//deactivation
register_deactivation_hook(__FILE__, array($VLBS, 'deactivate'));

但是,它不适用于使用 Yootheme Pro Pagebuilder 构建的页面。函数 new_content() 中所做的任何事情都是在内容加载后处理的。因此,我无法在它显示给用户之前对其进行操作。

所以问题是:如何在页面显示之前获取页面的内容?是否有相当于 Wordpress 的“the_content”?

非常感谢任何帮助!非常感谢您提前。

最好的问候法比安

Yootheme:1.22.5
Wordpress:5.2.4
PHP:7.3
浏览器:在 Chrome、Firefox、Edge、Internet Explorer 上测试

4

1 回答 1

0

在您的代码中,您确定这是 add_filter content 的良好用法吗?

在 doc中,第二个参数是字符串,而不是数组:

add_filter( 'the_content', 'filter_the_content_in_the_main_loop' );

function filter_the_content_in_the_main_loop( $content ) {

    // Check if we're inside the main loop in a single post page.
    if ( is_single() && in_the_loop() && is_main_query() ) {
        return $content . esc_html__("I'm filtering the content inside the main loop", "my-textdomain");
    }

    return $content;
}

在 wordpress 中,the_content函数显示内容。get_the_content还有其他功能

转到您的页面文件并获取内容。您可以使用 str_replace 并在之后回显新内容。

示例 single.php :

if ( $query->have_posts() ) :               
    while( $query->have_posts() ) : $query->the_post();

        $content = get_the_content();

        $new_content = str_replace(search, replace, $content);

        echo $new_content;

    endwhile;
endif;

如果您无法做到,请尝试使用输出缓冲区功能。如果您需要使用此功能,我会说,我会开发更多这部分。但是之前测试过上面的解决方案。

哦,它存在一个特殊的 WP 社区,您的问题将更加相关:https ://wordpress.stackexchange.com/

于 2019-11-25T16:34:26.733 回答