Intermediate WordPress Examples - Using Your Custom Post Type

In response to a previous article which covers custom WordPress plugin structure, How to Write a WordPress Plugin, a reader asked me for the following elaboration.

I’m relatively new to WP but I have a lot of experience with PHP and a
few other languages (still not great with OO though). I’m having a
hard time figuring out how to dynamically create posts using this
example plugin framework. Does the $_meta need to be submitted with
the wp_insert_post or do I need to call the save_post function after
the fact and provide the $_meta to it?

I am trying to import a bunch of posts from external DB data. The
admins need to be able to import/update all the posts at once, I’m
still working out the insert/update logic but that’s not really part
of the problem I am presently having.

If you could provide a simple example of programmatically creating a
new post w/ meta that would work with this example that would be
epic…

Thanks a ton for any input you can provide, WDP

This covers a few examples showing some post manipulation integrated into my plugin structure.

###For the first Question

I’m having a hard time figuring out how to dynamically create posts using this example plugin framework.

My plugin does not replace any of the regular WordPress functionality. Creating posts from your Custom Post Type is as simple as calling the stock WordPress functions: wp_insert_post .

// Create post object
$my_post = array(
    'post_title' => 'My Post Title',
    'post_content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean metus mauris, consectetur eget pharetra eu, varius et enim. Donec non feugiat sapien.',
    'post_status' => 'publish',
    'post_type' => 'the_name_of_your_custom_post_type'
);

// Insert the post into the database
wp_insert_post($my_post);

see http://codex.wordpress.org/Function_Reference/wp_insert_post

The real magic here is the 'post_type' => 'the_slug_of_your_custom_post_type' line in the $my_post array definition. All you need to do is change out the 'the_slug_of_your_custom_post_type' line with the slug of your post type.

###Dealing with Post Meta

Does the $_meta need to be submitted with
the wp_insert_post or do I need to call the save_post function after
the fact and provide the $_meta to it?

My first inclination was to tell you to handle the Post Meta manually and not rely on save_post… But thats a dodge, so I delved into the codex/code to figure out how the save_post hook works.

save_post is an action triggered whenever a post or page is created or
updated, which could be from an import, post/page edit form, xmlrpc,
or post by email. The data for the post is stored in $_POST, $_GET or
the global $post_data, depending on how the post was edited. For
example, quick edits use $_GET.

see http://codex.wordpress.org/Plugin_API/Action_Reference/save_post

So as long as your meta key=>values are in either $_POST, $_GET or the global $post_data arrays then everything is going to work out. A downside to my plugin template is that the save_post function for a CPT only looks at $_POST. In the situation where you are programmatically creating posts, $_POST is empty and the save_post for your CPT will not execute.

###We can fix this

Lets change up our save_post function to look at global $post_data if $_POST is empty.

/**
 * Save the metaboxes for this custom post type
 */
public function save_post($post_id)
{
    // verify if this is an auto save routine. 
    // If it is our form has not been submitted, so we dont want to do anything
    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
    {
        return;
    }

    $data = array();
    if(isset($_POST['post_type']))
    {
        $data = $_POST;
    }
    else
    {
        global $post_data;
        $data = $post_data;
    }

    if($data['post_type'] == self::POST_TYPE && current_user_can('edit_post', $post_id))
    {
        foreach($this->_meta as $field_name)
        {
            // Update the post's meta field
            update_post_meta($post_id, $field, $data[$field_name]);
        }
    }
    else
    {
        return;
    } // if($data['post_type'] == self::POST_TYPE && current_user_can('edit_post', $post_id))
} // END public function save_post($post_id)

###Programmatic Post Meta

That solves the biggest problem we introduced in the last tutorial. But how do you actually go about attaching your meta programmatically to the post?

// Create post object
$my_post = array(
    'post_title' => 'My Post Title',
    'post_content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean metus mauris, consectetur eget pharetra eu, varius et enim. Donec non feugiat sapien.',
    'post_status' => 'publish',
    'post_type' => 'the_name_of_your_custom_post_type'
);

global $post_data;
$post_data = array(
    'post_type' => 'the_name_of_your_custom_post_type',
    'meta_a' => 'meta_value_a',
    'meta_b' => 'meta_value_b'
);

// Insert the post into the database
wp_insert_post($my_post);

Call the global $post_data and populate it with the post_type and your meta key=>values before calling wp_insert_post.

Written on January 31, 2013