'My new post', 'post_content' => 'Content to insert.', 'post_status' => 'publish', 'post_author' => get_current_user_id(), ); // Insert the post into the database. $post_id = wp_insert_post( $new_post ); if ( $post_id ) { // Get the full URL of the local image in the theme's assets folder. $image_url = get_theme_file_uri( 'assets/my-image.jpg' ); // Include required WordPress files for media handling. require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/file.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); // Download image and attach to post. $attachment_id = media_sideload_image( $image_url, $post_id, null, 'id' ); if (! is_wp_error( $attachment_id )) { set_post_thumbnail( $post_id, $attachment_id ); // Use transients to display a notice on the next page load. set_transient( 'sample_post_notice', 'success', 45 ); } else { set_transient( 'sample_post_notice', 'image_error', 45 ); } } else { set_transient( 'sample_post_notice', 'post_error', 45 ); } } add_action( 'after_switch_theme', 'create_sample_post_with_image' ); // Display admin notices if needed. add_action( 'admin_notices', 'sample_post_admin_notice' ); function sample_post_admin_notice() { $notice = get_transient( 'sample_post_notice' ); if ( $notice === 'success' ) { echo '
Post created with featured image!
Post created, but image failed.
Post creation failed.