Question

I am attempting to publish HTML generated from an external party within Wordpress, but I am getting very inconsistent results with style attribute on all HTML elements, in that if I programmatically update the post the style attributes get removed, but if I publish the same HTML via the editor it remains untouched. Debugging so far it looks like the kses filter is what is performing the actual stripping

Original HTML:

<div class="container-fluid " style="background-image:url('https://localhost/app/uploads/2018/08/315.png');"></div>

When submitted programmatically it becomes:

<div class="container-fluid "></div>

The code that does the submitting (modified to be clearer example)

$body = <<<EOT
<div class="container-fluid " style="background-image:url('https://localhost/app/uploads/2018/08/315.png');"></div>
EOT;

$new_post = [
    'ID'                => 70,
    'post_title'        => 'Example',
    'post_content'      => $body,
    'post_type'         => 'post',
    'post_status'       => 'draft'
];
$success = wp_update_post($new_post, true);

The goal is to avoid the stripping in a normal environment

Envionment:

  • Wordpress 4.9.6
  • No additional plugins outside of the one this code resides in
  • Default theme
Was it helpful?

Solution

This is because what you're trying to do trips a security feature, post content is passed through wp_kses_post to strip out dangerous tags

Administrators however, have the unfiltered_html capability, which allows them to put arbitrary dangerous HTML in content and titles. This is why you're able to insert the tags via the editor.

This still doesn't address the root problem though, that you're including style tags in post content, which is bad practice, and can cause other issues.

Instead, use shortcodes to embed arbitrary HTML in content, e.g. implement a fluid container shortcode:

[fluidcontainer background="url"][/fluidcontainer]

Or use a CSS HTML solution that does not require a style tag


As an aside, there is an extremely dangerous solution, that some might suggest, which would be to strip out the security feature. This would be extremely dangerous, and open you up to a large array of attacks. As I have already demonstrated, it is unnecessary. Be very wary of anybody who might suggest it. To do so would be reckless and irresponsible, and on some levels unethical. It could also be used as grounds of technical negligence during compliance, audits, or investigations of data breaches

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top