• Resolved WP Libra

    (@wpbum)


    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.

Viewing 4 replies - 1 through 4 (of 4 total)
  • 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). https://codex.www.ads-software.com/Function_Reference/wp_insert_post

    Thread Starter WP Libra

    (@wpbum)

    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?

    Looks good to me!

    Thread Starter WP Libra

    (@wpbum)

    Yup. Tested as described and worked.

    Thanks!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How To Set post_id For Custom Post Type’ is closed to new replies.