Skip to content

Instantly share code, notes, and snippets.

@seankmchenry
Last active July 19, 2020 18:24
Show Gist options
  • Save seankmchenry/8831474 to your computer and use it in GitHub Desktop.
Save seankmchenry/8831474 to your computer and use it in GitHub Desktop.
WP Insert Post w/Image Handling
<?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 );
@ddimitrioglo
Copy link

Thanks for example.
After some investigation found out that there is a wp cli, which can help.

class ImportPosts
{
    private const IMPORT_IMAGE_CMD = 'wp media import %s --post_id=%u --preserve-filetime --porcelain';
    private const CREATE_POST_CMD = <<<STR
wp post create %s \
    --post_title='%s' \
    --post_date='%s' \
    --tags_input='%s' \
    --post_category='%s' \
    --post_name='%s' \
    --post_author='admin' \
    --post_status=publish \
    --format=json \
    --porcelain
STR;

    protected function exec(): void
    {
         $postId = shell_exec(sprintf(self::CREATE_POST_CMD, <params> ));
         $parsedPostId = intval($postId);
         shell_exec(sprintf(self::IMPORT_IMAGE_CMD, <params>));
    }
}

and it worked like a charm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment