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

I’d like to find a way to fill some of the fields from the /wp-admin/post-new.php page from an external source.

It works for the title: loading /wp-admin/post-new.php?post_title=title1 fills the title input with title1.

Read More

You get the idea, what would be great is something like /wp-admin/post-new.php?post_title=title1&content=content1&tags=tag1,tag2&cat=cat1,cat2… so that when I arrive on the post-new.php with most fields already filled from an outside script.

I would need to fill in custom fields as well.

How can I do that? What’s the best option? A full external script that connects to the base my himself and run insert queries? A plugin? If so, do you have some suggestions?

Related posts

Leave a Reply

3 comments

  1. 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.

  2. If this is to add end-users then maybe the easiest thing to do is to create a jQuery script to assign the values. Here’s how to parse the URL:

    And here’s how to add Javascript in WordPress:

    Finally, just view source in the WordPress edit screen to see the names of the input fields and then this shows how to use jQuery to assign values: