mercredi 22 avril 2015

wp_insert_post not working correctly with custom_post_type

This is the code I use to register my custom post-type:

// Register Projects custom post-type
add_action('init', 'projects_register');
function projects_register() {
    $labels = array(
        'name' => _x('Projects', 'post type general name'),
        'singular_name' => _x('Project', 'post type singular name'),
        'add_new' => _x('Add New', 'project'),
        'add_new_item' => __('Add New Project'),
        'edit_item' => __('Edit Project'),
        'new_item' => __('New Project'),
        'view_item' => __('View Project'),
        'search_items' => __('Search Projects'),
        'not_found' =>  __('No projects found'),
        'not_found_in_trash' => __('No projects found in Trash'),
        'parent_item_colon' => ''
    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'show_ui' => true,
        'query_var' => true,
        'menu_icon' => 'dashicons-plus-alt',
        'rewrite' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => 20,
        'can_export' => true,
        'supports' => array('title','editor','custom-fields','thumbnail')
    register_post_type( 'projects' , $args );

And this is the function where I (supposedly) add new posts to my custom post-type:

// Create new post from form data
function save_project_submission($cfdata) {

    $formtitle = $cfdata->title;
    $formdata = $cfdata->posted_data;   

    if ( $formtitle == 'Form Title') {

        $the_title = $formdata['post_title'];
        $the_content = $formdata['post_content'];

        // Create new post
        $newpostid = wp_insert_post(array(
            'post_type' => 'projects',
            'post_title' => $the_title,
            'post_content' => $the_content,
            'post_status' => 'pending',
            'comment_status' => 'closed'
        ), true);

        // Add meta data for the new post
        add_post_meta($newpostid, 'sample_meta_data1', $formdata['name']);
        add_post_meta($newpostid, 'sample_meta_data2', $formdata['address']);

add_action('wpcf7_before_send_mail', 'save_project_submission', 1);

Expected behaviour:

  1. Form is submitted

  2. New PENDING post is created under custom post-type "projects" (with data from the form)

Current behavior:

  1. Form is submitted

  2. New PUBLISHED post is created under "posts" (with data from the form, but with empty custom fields)

  3. New PENDING post is created under "projects" (without data from the form, e.g. "no title", no "post content", no custom fields)

Everything looks correct code-wise to me, and I can't figure out why I am not achieving the expected behaviour. Thanks for your help.

Aucun commentaire:

Enregistrer un commentaire