Last active
July 19, 2020 18:24
-
-
Save seankmchenry/8831474 to your computer and use it in GitHub Desktop.
WP Insert Post w/Image Handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Set new post and post ID variables | |
$args = array( | |
'post_title' => $post_title, | |
'post_content' => $post_content, | |
'post_status' => 'draft', | |
'post_type' => $post_type | |
); | |
$new_post = wp_insert_post( $args ); | |
// Insert image into media library | |
if ( isset( $feat_img ) ) { | |
// load required files | |
require_once( ABSPATH . 'wp-admin/includes/media.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
// use media_handle_upload rather than wp_insert_attachment | |
$attach_id = media_handle_upload( 'namespace_feat_img', $new_post ); | |
} | |
// Update post meta | |
update_post_meta( $new_post, 'namespace_post_meta1', $post_meta1 ); | |
update_post_meta( $new_post, 'namespace_post_meta2', $post_meta2 ); | |
set_post_thumbnail( $new_post, $attach_id ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for example.
After some investigation found out that there is a wp cli, which can help.
and it worked like a charm!