Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

php - Wordpress preg_replace ' ' tags in post_content with insert_post_data not working

I have   tags as spaces in autocreated posts in Wordpress and trying to replace them before posting/saving. Text sample below:

This is an Example of how my text looks

Believe this code placed in "functions.php" should replace the tags with spaces

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

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

But this doesn't work.

  • I tested the regex and it works.
  • when I change the pattern to a word in the text it works

But not with the   tags in the html...

Any idea?

EDIT 1

when dumping $data as suggested using var_dump($data['post_content']); die;

creating a new post manually, opens blank window with:

array(21) { ["post_author"]=> int(1) ["post_date"]=> string(19) "2021-01-26 17:15:29" ["post_date_gmt"]=> string(19) "0000-00-00 00:00:00" ["post_content"]=> string(0) "" ["post_content_filtered"]=> string(0) "" ["post_title"]=> string(10) "Auto Draft" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(10) "auto-draft" ["post_type"]=> string(4) "post" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(4) "open" ["post_password"]=> string(0) "" ["post_name"]=> string(0) "" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2021-01-26 17:15:29" ["post_modified_gmt"]=> string(19) "0000-00-00 00:00:00" ["post_parent"]=> int(0) ["menu_order"]=> int(0) ["post_mime_type"]=> string(0) "" ["guid"]=> string(0) "" }

EDIT 2 This with xA0or '?' did not work

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

function nbsp_remover($data) {
    return str_replace('xA0', '', $data); 
}
question from:https://stackoverflow.com/questions/65904955/wordpress-preg-replace-nbsp-tags-in-post-content-with-insert-post-data-not-w

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ok, I solved my issue by circumventing it...

As noted above I couldn't find a way to remove the   tags from the post content.

I was able to edit the posts before they got send and read by wordpress. So I replaced all spaces with a special character before the post got created in WP and than used the regex code to replace that character with spaces.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...