0

I`am trying to clean style attr from tags when saving posts and products but nothing happend. (I checked my regexp on https://regex101.com/)

function filter_style_save($content) {
$re = '/(<[^>]+)(style=".*?")/';
$replace = "$1";
$content1 = preg_replace($re, $replace, $content);
$content = $content1;
return $content;
};
add_filter('content_save_pre', 'filter_style_save', 99, 2);

UPD. I have updated regex to match success result on regex101

    (<[^>]+)(style=".*?")

I expect that attribute STYLE will be deleted with all its content:

<ul>
<li style="padding: 5px 0;">Wooden part</li>
<li class="red" style="padding: 5px 0;">Metall top plate</li>
<li style="padding: 5px 0;">Metall front logo</li>
</ul>
//Should be like this
<ul>
<li >Wooden part</li>
<li class="red">Metall top plate</li>
<li >Metall front logo</li>
</ul>

UPD 2. I stoped at using filter wp_insert_post_data.

function filter_style_save1($data, $postarr) {
$content = $data['post_content'];

$re = '/(<[^>]+)(style=".*?")/';
$replace = "$1";
$content = preg_replace($re, $replace, $content);

$data['post_content'] = $content;
//error_log( print_r(  $data['post_content'], true ) );
return $data;
};
add_filter('wp_insert_post_data', 'filter_style_save1', 10, 2);

Error log shows the right content, but post_content wasn't replaced.

UPD 3. Also I have noticed that when I duplicate the post - error log shows <li style="padding: 5px 0;">Metall front logo</li> and when I update existing post, it shows <li style=\"padding: 5px 0;\">Metall front logo</li> with slashes. Maybe this cause the problem with regex. But why they appear I don't understand.

  • You haven't explained how your regex should work. Please provide possible inputs and the expected output. – Picard Jun 28 '17 at 12:32
  • Also - are you checking content that's already been created? The content_save_pre filter works on new content, but will not fix old content. – WebElaine Jun 28 '17 at 16:36
  • @WebElaine I tried to add $content .= 'text ' . $content; return $content; and these changes were saved. But you right, when I clone this post, it was filtered. What filter can you recommend? I tried action save_post but can't to replace post_content with my content. Is it right choice? – Karin Kador Jun 28 '17 at 17:32
  • I also tried wp_insert_post_data but also can't replace the content. – Karin Kador Jun 28 '17 at 17:44
  • A filter on the_content is probably what you need. Unless you go back and clean out the previously saved data, you're stuck filtering the content that is already saved. codex.wordpress.org/Plugin_API/Filter_Reference/the_content – WebElaine Jun 28 '17 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.