I have a custom post type to which I’d like to programmatically import data. I have followed these instructions and these, and I can easily do it for WP typical pages and posts.
However, my custom post type has custom fields for, for example, longitude and latitude. How do I figure how how those names (array keys) should be referred to in the post array?
$defaults = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'custom-post-type',
longitude => $my_long, // <- what's the key here?
latitude => $my_lat // <- what's the key here?
);
$images = array_of_images; // <- how do these get added?
There are about 40 extra fields I have to add data to.
Additionally, each of my items of content has image attachments, and I want to programmatically add those as well (either from a URL or from my local hard drive, whichever approach is best).
As an answer, I’m looking for a very simple, but fully functioning script (or at least fully complete pseudo code) that would take into account all the programmatic steps I need to take to get a post into the database with it’s related image attachments. The result should be the same as if I filled out all the fields, uploaded media, and hit “Publish” from within WordPress.
4 Answers
You should first run the wp_insert_post()
which will return the post ID. Then use that post ID to add your custom fields. Use add_post_meta()
to add the custom fields.
$post_id = wp_insert_post( $args );
add_post_meta( $post_id, 'longitude', $my_long );
add_post_meta( $post_id, 'latitude', $my_lat );
For image attachments, you can refer to this question: How to set featured image to custom post from outside programmatically