[resolved] How To Set post_id For Custom Post Type (5 posts)

  1. Aaron
    Posted 2 years ago #

    I am creating a plugin that gets an array from external source and I want to add this to a custom post type which is already created.

    I am just using something simple like the below right now

    add_post_meta( $post->ID, product_price, $import_price );
    add_post_meta( $post->ID, product_discount_price, $import_discount );
    add_post_meta( $post->ID, product_excerpt, $import_excerpt );
    add_post_meta( $post->ID, product_sku, $import_sku );
    add_post_meta( $post->ID, product_url, $import_url );

    My issue is I am creating a new entry so I don't know the post_id. Is there a way to default it so it generates the next one available?

    I've also tried $post_id. But if I replace it with a number manually instead of a variable it works great.

    Any assistance is appreciated.

  2. webbtj
    Posted 2 years ago #

    Are you creating the post first? If you can create the post with wp_insert_post it will return the ID of the new post (assuming there were no errors). http://codex.wordpress.org/Function_Reference/wp_insert_post

  3. Aaron
    Posted 2 years ago #

    No I am not. Guess I was going about this wrong.

    So what you are saying is I import my data from an array. Then since my custom post type only uses the title I would just do something like.

    $my_post = array(
      'post_title'    => wp_strip_all_tags( $_POST['post_title'] ),
      'post_status'   => 'publish',
      'post_author'   => 1,
    $post_id = wp_insert_post( $my_post, $wp_error );

    Now it created a post with a title and everything else is blank and I have $post_id from that which I can add to the post_meta under that ID.

    Does that sound right?

  4. webbtj
    Posted 2 years ago #

    Looks good to me!

  5. Aaron
    Posted 2 years ago #

    Yup. Tested as described and worked.


Topic Closed

This topic has been closed to new replies.

About this Topic


No tags yet.