Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using the save_post action to save some meta data in a custom post type:

function my_save_post($post_id) {
    // is autosave?
    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }

    // verify nonce
    if ( !wp_verify_nonce( $_POST['metabox_nonce'], basename(__FILE__) )) {
        return $post_id;
    }

    if ('book' == $_POST['post_type']) {
        $post_parent = intval($_POST['post_parent']);
        $author = $_POST['author'];
        $price = intval($_POST['price']);
        update_post_meta($post_id, 'author', $author);
        update_post_meta($post_id, 'price', $price);

        //TODO: add function to update the post_parent field
    }
}

My question is, how can I modify the custom post type's post_parent field? As I understand, I can't use the update_post_meta() function because the post_parent field is not a meta field. Am I right?

Any help would be appreciated

share|improve this question

2 Answers 2

A very simple and quick solution could be something like:

$wpdb->query( 'update '.$wpdb->prefix.'posts set post_parent='.$post_parent.' where ID='.$post_id );

and you might need to add the global $wpdb;

If you are not using the update at the save_post hook (like if you are updating the metaboxes of your custom post type), you could, instead, use:

  $bookUpdate = array();
  $bookUpdate['ID'] = $post_id;
  $bookUpdate['post_parent'] = $post_parent;

  wp_update_post( $bookUpdate );
share|improve this answer

You could use the wp_insert_post_data filter instead, which gives you direct access to the post's data.

function wpa_insert_post( $data , $postarr ){ 
    //do something with $data['post_parent']
    return $data;
}
add_filter( 'wp_insert_post_data' , 'wpa_insert_post' , '99', 2 );

UPDATE:

I added the following to your code and it's working:

function wpa_insert_post( $data , $postarr ){ 
    //do something with $data['post_parent']
    $data['post_parent'] = intval($postarr['post_parent']);

    //update meta data
    update_post_meta($postarr['ID'], 'author', $postarr['author']);
    update_post_meta($postarr['ID'], 'price', $postarr['price']);

    return $data;
}
add_filter( 'wp_insert_post_data' , 'wpa_insert_post' , '99', 2 );
share|improve this answer
    
And how can I save the metadata using this filter? –  user1991185 May 29 '13 at 19:41
    
@user1991185 sorry, just getting back to this- it seems you've figured it out, yes? –  Milo May 29 '13 at 22:12
    
Yes, I figured it out. Thanks! –  user1991185 May 29 '13 at 22:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.