0
0
WordpressHow-ToBeginner · 3 min read

How to Create a Draft in WordPress Quickly and Easily

To create a draft in WordPress, you can use the admin dashboard by clicking Posts > Add New and then selecting Save Draft. Alternatively, programmatically create a draft post using the wp_insert_post function with the post_status set to draft.
📐

Syntax

To create a draft post programmatically in WordPress, use the wp_insert_post function with an array of post data. Key parts include:

  • post_title: The title of the post.
  • post_content: The main content body.
  • post_status: Set to draft to save as draft.
  • post_type: Usually post for blog posts.
php
<?php
$post_data = array(
  'post_title'    => 'My Draft Post',
  'post_content'  => 'This is the content of the draft.',
  'post_status'   => 'draft',
  'post_type'     => 'post'
);
$post_id = wp_insert_post($post_data);
?>
💻

Example

This example shows how to create a draft post named "My Draft Post" with some content using PHP code in a WordPress plugin or theme file.

php
<?php
function create_sample_draft() {
  $post_data = array(
    'post_title'    => 'My Draft Post',
    'post_content'  => 'This is the content of the draft.',
    'post_status'   => 'draft',
    'post_type'     => 'post'
  );
  $post_id = wp_insert_post($post_data);
  if (is_wp_error($post_id)) {
    return 'Error creating draft.';
  }
  return 'Draft created with ID: ' . $post_id;
}

// Call the function and echo result
echo create_sample_draft();
?>
Output
Draft created with ID: 123
⚠️

Common Pitfalls

Common mistakes when creating drafts in WordPress include:

  • Not setting post_status to draft, which publishes the post immediately.
  • Forgetting to specify post_type, which defaults to post but can cause issues if custom post types are used.
  • Not checking for errors returned by wp_insert_post.
  • Trying to create drafts outside WordPress context without loading WordPress functions.
php
<?php
// Wrong: post_status missing, post publishes immediately
$post_data_wrong = array(
  'post_title' => 'Wrong Post',
  'post_content' => 'Content here'
);
wp_insert_post($post_data_wrong); // This publishes the post

// Right: post_status set to draft
$post_data_right = array(
  'post_title' => 'Right Draft',
  'post_content' => 'Content here',
  'post_status' => 'draft'
);
wp_insert_post($post_data_right);
📊

Quick Reference

Summary tips for creating drafts in WordPress:

  • Use the admin dashboard: Posts > Add New then click Save Draft.
  • Programmatically use wp_insert_post with post_status set to draft.
  • Always check for errors after inserting posts.
  • Specify post_type if using custom post types.

Key Takeaways

Set post_status to 'draft' to create a draft post in WordPress.
Use wp_insert_post function for programmatic draft creation.
Always check for errors after inserting a post.
You can save drafts easily from the WordPress admin dashboard.
Specify post_type when working with custom post types.