Pre-fill fields with content from outside when creating a new post

An empty post is created by get_default_post_to_edit(). This function reads the post_title, content and excerpt values in the $_REQUEST array, and also filters them through default_title, default_content and default_excerpt.

By default this function only returns a “fake” $post object, but if the $create_in_db parameter is set to true, it is actually saved in the database with the post_status set to auto-draft.

This parameter is set in post-new.php, which means you can hook into wp_insert_post and save extra stuff, like tags, from the $_REQUEST array or from an external source. A very simple example:

add_action( 'load-post-new.php', 'wpse8650_post_new' );
function wpse8650_post_new()
{
    add_action( 'wp_insert_post', 'wpse8650_wp_insert_post_default' );
}

function wpse8650_wp_insert_post_default( $post_id )
{
    add_post_meta( $post_id, 'wpse8650_meta_key', $_REQUEST['meta_value'] );
    wp_set_post_tags( $post_id, $_REQUEST['tags']) );
}

This works because the custom fields and post tags are read again from the database (or the cache) when building the page, and we do this before these metaboxes are displayed.

Leave a Comment