使用 PHP 在 WordPress 中动态包装字符串



问题

如何替换®符号以<sup>&reg;</sup> .更具体地说,在WordPress项目中最干净的方法是什么?

背景

我有一个Javascript解决方案,可以在我的CodePen中工作。

但我希望这发生在服务器上,而不是客户端。将其放入WP项目的最佳标准位置在哪里?我的任务只是维护一个主题,所以把它放在那里,但具体在哪里?

此外,代码仅替换了第一个®.所以我需要循环它。


法典

爪哇语

function regReplace() {
    var regStr = document.getElementById("target-div").innerHTML; 
    var resSup = regStr.replace("®", "<sup>&reg;</sup>");
    document.getElementById("target-div").innerHTML = resSup;
}
regReplace();

最简单的方法是使用过滤器挂接到the_content。它工作所需要的只是一个过滤器函数,用另一个子字符串替换你的子字符串。

站点范围的替换

这会将所有用户®生成的内容中的所有匹配项替换为所需的 HTML。

add_filter('the_content', 'replace_stuff');
function replace_stuff($content) {
    return str_replace("®", "<sup>&rep;</sup>", $content);
}

仅在特定页面上替换

这将仅替换与此处指定为 'your-slug' 的 slug 匹配的页面上出现的所有实例。

add_filter('the_content', 'maybe_replace_stuff');
function maybe_replace_stuff($content) {
    $post = get_post();
    $slug = $post->post_name;
    if ($slug === 'your-slug') {
        $content = str_replace("®", "<sup>&rep;</sup>", $content);
    }
    return $content;
}

仅在一组特定页面上替换

与上面几乎相同,除了需要检查多个页面 slug。

add_filter('the_content', 'maybe_replace_stuff');
function maybe_replace_stuff($content) {
    $acceptedSlugs = array('foo', 'bar');
    $post = get_post();
    $slug = $post->post_name;
    if (in_array($slug, $acceptedSlugs)) {
        $content = str_replace("®", "<sup>&rep;</sup>", $content);
    }
    return $content;
}

仅当帖子使用特定模板时才替换

add_filter('the_content', 'maybe_replace_stuff');
function maybe_replace_stuff($content) {
    $post = get_post();
    $template = get_post_meta($post->ID, '_wp_page_template', true);
    if ($template === 'your-template.php') {
        $content = str_replace("®", "<sup>&rep;</sup>", $content);
    }
    return $content;
}