【问题标题】:Wordpress preg_replace ' ' tags in post_content with insert_post_data not workingWordPress preg_replace ' ' post_content 中的标签与 insert_post_data 不起作用
【发布时间】:2021-04-30 10:47:58
【问题描述】:

我在 Wordpress 中自动创建的帖子中有   标签作为空格,并尝试在发布/保存之前替换它们。下面的文本示例:

This is an Example of how my text looks

相信放在“functions.php”中的这段代码应该用空格替换标签

add_filter( 'wp_insert_post_data' , 'nbsp_remover' , '99', 2 );

function nbsp_remover($data) {
    $pattern = '/\&nbsp\;/';
    $data['post_content'] = preg_replace($pattern, ' ', $data['post_content']);
    return $data;
}

但这不起作用。

  • 我测试了正则表达式,它工作正常。
  • 当我将模式更改为文本中的一个单词时,它会起作用

但不是在 html 中使用   标记...

有什么想法吗?

编辑 1

当使用 var_dump($data['post_content']); die; 建议转储 $data 时

手动创建新帖子,打开空白窗口:

array(21) { ["post_author"]=> int(1) ["post_date"]=> string(19) "2021-01-26 17:15:29" ["post_date_gmt"]=> 字符串(19) "0000-00-00 00:00:00" ["post_content"]=> 字符串(0) "" ["post_content_filtered"]=> string(0) "" ["post_title"]=> string(10) "自动草稿" ["post_excerpt"]=> 字符串(0) "" ["post_status"]=> 字符串(10) "auto-draft" ["post_type"]=> string(4) "post" ["comment_status"]=> 字符串(4)“打开”[“ping_status”]=>字符串(4)“打开” ["post_password"]=> 字符串(0) "" ["post_name"]=> 字符串(0) "" ["to_ping"]=> 字符串(0) "" ["pinged"]=> 字符串(0) "" ["post_modified"]=> 字符串(19) "2021-01-26 17:15:29" [“post_modified_gmt”]=> 字符串(19)“0000-00-00 00:00:00” ["post_parent"]=> int(0) ["menu_order"]=> int(0) ["post_mime_type"]=> 字符串(0) "" ["guid"]=> 字符串(0) "" }

编辑 2 这与 \xA0or ' ' 不起作用

add_filter( 'wp_insert_post_data' , 'nbsp_remover' , '99', 2 );

function nbsp_remover($data) {
    return str_replace('\xA0', '', $data); 
}

【问题讨论】:

  • 文本示例是您在$data 中的内容?可以在preg_replace 之前添加var_dump($data['post_content']); 的输出吗?
  • 我忘了补充说我是 WP 的初学者,这是第一次尝试 php 脚本,所以不知道你在建议什么@ChinLeung
  • var_dump($data['post_content']); die; 添加为nbsp_remover 函数的第一行,并尝试创建一个新帖子。它将显示$data['post_content'] 的内容,并将其复制粘贴到您的问题中。 :)
  • 我添加了这一行 - 现在当我尝试手动添加新帖子时,我得到一个白屏说明: - string(0) "" -
  • 很可能你所有的 都已经变成\xA0,试试return str_replace('\xA0', '', $data);。顺便说一句,您没有在函数中使用$postarr 变量。

标签: php wordpress preg-replace


【解决方案1】:

好的,我通过绕过它解决了我的问题......

如上所述,我找不到从帖子内容中删除   标记的方法。

我能够在它们被 wordpress 发送和阅读之前对其进行编辑。所以我在 WP 中创建帖子之前用特殊字符替换了所有空格,然后使用正则表达式代码用空格替换了该字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-11
    • 2014-10-31
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多