wp_write_post

函数
wp_write_post ( No parameters )
返回值
  • (int|WP_Error) Post ID on success, WP_Error on failure.
定义位置
相关方法
write_postwp_remote_postwp_update_postwp_insert_postwp_delete_post
引入
2.1.0
弃用
-

wp_write_post – 这个函数用来创建或更新一个WordPress文章。它负责插入或更新数据库中的文章数据,以及更新相关的文章元和分类数据。

从"Write Post"表单中使用`$_POST’信息创建一个新文章。

function wp_write_post() {
	if ( isset( $_POST['post_type'] ) ) {
		$ptype = get_post_type_object( $_POST['post_type'] );
	} else {
		$ptype = get_post_type_object( 'post' );
	}

	if ( ! current_user_can( $ptype->cap->edit_posts ) ) {
		if ( 'page' === $ptype->name ) {
			return new WP_Error( 'edit_pages', __( 'Sorry, you are not allowed to create pages on this site.' ) );
		} else {
			return new WP_Error( 'edit_posts', __( 'Sorry, you are not allowed to create posts or drafts on this site.' ) );
		}
	}

	$_POST['post_mime_type'] = '';

	// Clear out any data in internal vars.
	unset( $_POST['filter'] );

	// Edit, don't write, if we have a post ID.
	if ( isset( $_POST['post_ID'] ) ) {
		return edit_post();
	}

	if ( isset( $_POST['visibility'] ) ) {
		switch ( $_POST['visibility'] ) {
			case 'public':
				$_POST['post_password'] = '';
				break;
			case 'password':
				unset( $_POST['sticky'] );
				break;
			case 'private':
				$_POST['post_status']   = 'private';
				$_POST['post_password'] = '';
				unset( $_POST['sticky'] );
				break;
		}
	}

	$translated = _wp_translate_postdata( false );
	if ( is_wp_error( $translated ) ) {
		return $translated;
	}
	$translated = _wp_get_allowed_postdata( $translated );

	// Create the post.
	$post_ID = wp_insert_post( $translated );
	if ( is_wp_error( $post_ID ) ) {
		return $post_ID;
	}

	if ( empty( $post_ID ) ) {
		return 0;
	}

	add_meta( $post_ID );

	add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );

	// Now that we have an ID we can fix any attachment anchor hrefs.
	_fix_attachment_links( $post_ID );

	wp_set_post_lock( $post_ID );

	return $post_ID;
}

常见问题

FAQs
查看更多 >