wp_insert_post() 与 PHP 的 HTML 标签

Dig*_*ine 2 html php wordpress

这个问题似乎没有答案。我发现自己陷入了困境。就这样

我在使用 WP API 插入带有 HTML 标签的帖子时遇到问题。

我使用的方法是:wp_insert_post(),内容如下:

$content = "<p> <img src="img-link"> </p> <p> Hi, this is an example of the content.</p> <a class="dl" href="link-address"> Link Name</a>";

我发布帖子时想要的结果是:

必要时应用 html 的格式化帖子。

但当我发布帖子时得到的结果是:

<p> <img src="img-link"> </p> <p> Hi, this is an example of the content.</p> <a class="dl" href="link-address"> Link Name</a>

当我转到 WP 编辑器直接编辑同一篇文章时,可视化编辑器看起来格式良好,符合预期

然后我导航到文本编辑器,也看到格式良好:

<p> <img src="img-link"> </p> <p> Hi, this is an example of the content.</p> <a class="dl" href="link-address"> Link Name</a>

很明显这就是我真正想要的。但是,当我按照前面所述从我的 php 文件中发布这篇文章时,我得到了这个发布:

<p> <img src="img-link"> </p> <p> Hi, this is an example of the content.</p> <a class="dl" href="link-address"> Link Name</a>

我的代码

$content="<p> <img src="img-link"> </p> <p> Hi, this is an example of the content.</p> <a class="dl" href="link-address"> Link Name</a>";

$my_post = array( 
'post_title' => $title, 
'post_status' => 'publish', 
'post_content' => $content,
'post_author' => 1, 
'post_category' => array(8,39)); 

$post_id = wp_insert_post( $my_post );
Run Code Online (Sandbox Code Playgroud)

我努力了 html_entity_decode($content);

remove_filter('content_save_pre', 'wp_filter_post_kses');

remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
Run Code Online (Sandbox Code Playgroud)

在插入数据库之前和

add_filter('content_save_pre', 'wp_filter_post_kses');

add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
Run Code Online (Sandbox Code Playgroud)

插入后

我的脚本只加载了wp-load.php

Dig*_*ine 5

显然这是一个最终有效的解决方案。

$title = "My news";
$content='<p> <img src="img-link"> </p> <p> Hi, this is an example of the content.</p> <a class="dl" href="link-address"> Link Name</a>';

$postData = array(
    'post_title' => $title,
    'post_status' => 'publish',
    'post_content' => $content,
    'post_author' => 1,
    'post_type'         =>   'post',
    'post_category' => array()
);

//Here is the Magic:
kses_remove_filters(); //This Turns off kses
$id = wp_insert_post($postData);
kses_init_filters(); //This Turns on kses again
Run Code Online (Sandbox Code Playgroud)

最初的问题是我提出的,并在stackexchange 上提供了解决方案 HERE