【问题标题】:How to have an empty post title and content when creating a new WordPress post via the front-end通过前端创建新的 WordPress 帖子时如何有一个空的帖子标题和内容
【发布时间】:2014-01-22 03:19:54
【问题描述】:

我的目标是通过我创建的自定义前端表单将新的草稿帖子插入数据库。我需要帖子标题和内容为空。这可能吗?

我尝试了以下不起作用:

$post_data = array(
    'post_title'    => '',
    'post_type'     => 'post',
    'post_content'  => '',
    'post_status'   => 'draft',
    'post_author'   => 1
);

$post_id = wp_insert_post( $post_data );

注意:您可以使用带有空标题和内容的后端编辑器创建新帖子,所以我想知道 WordPress 的人是如何做到的。

【问题讨论】:

  • 你有什么错误吗? wp_insert_post( $post_data, true ); 应该返回一些:)
  • 是的,我得到一个“内容、标题和摘录”是空的。 var转储:object(WP_Error)#34 (2) { ["errors"]=> array(1) { ["empty_content"]=> array(1) { [0]=> string(38) "内容,标题,摘录为空。” } } ["error_data"]=> 数组(0) { } }

标签: php wordpress forms


【解决方案1】:

你不能用wp_insert_post插入空白帖子,Wordpress会用wp_insert_post_empty_content钩子阻止它,你可以在源代码中看到它:https://developer.wordpress.org/reference/functions/wp_insert_post/

唯一的办法就是用一个自定义函数绕过这个钩子

这是一个例子 (source)

add_filter('pre_post_title', 'wpse28021_mask_empty');
add_filter('pre_post_content', 'wpse28021_mask_empty');
function wpse28021_mask_empty($value)
{
    if ( empty($value) ) {
        return ' ';
    }
    return $value;
}

add_filter('wp_insert_post_data', 'wpse28021_unmask_empty');
function wpse28021_unmask_empty($data)
{
    if ( ' ' == $data['post_title'] ) {
        $data['post_title'] = '';
    }
    if ( ' ' == $data['post_content'] ) {
        $data['post_content'] = '';
    }
    return $data;
}

【讨论】:

  • 很好的解决方案。谢谢!
【解决方案2】:

WordPress 核心中有一个过滤器可以用来防止这种情况发生。

wp_insert_post_empty_content

https://developer.wordpress.org/reference/hooks/wp_insert_post_empty_content/

你应该可以使用如下:

add_filter( 'wp_insert_post_empty_content', '__return_false' );

$post = wp_insert_post( $post_args );

【讨论】:

    猜你喜欢
    • 2020-04-15
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    相关资源
    最近更新 更多