If you have the image in your media library you can just loop trough them and create post via wp_insert_post
.
function import_post_from_imgs() {
$images = get_posts('post_type=attachment&post_status=inherit&posts_per_page=-1');
// just a minimal security check
if ( ! current_user_can('publish_posts') ) return;
if ( ! empty($images) ) { foreach ( $images as $image) {
// prevent duplicate if for some reason the function is called more than once
if ( get_post_meta($image->ID, '_imported', true) ) continue;
$post = array(
'post_title' => $image->post_title,
'post_content' => '',
'post_content' => 'publish'
);
// insert post
$postid = wp_insert_post( $post );
if ( $postid ) {
// set the image as thumbnalil
set_post_thumbnail($postid, $image->ID);
update_post_meta($image->ID, '_imported', 1);
}
} }
}
function go_import_post_from_imgs() {
if ( isset($_GET['import_images']) ) import_post_from_imgs();
}
add_action('admin_init', 'go_import_post_from_imgs');
In code above the import function is triggered on admin init, when the $_GET
variable ‘import_images’ is setted.
So, you have to login into your dashboard and then the url of your page is sonething like http://example.com/wp-admin/
. Now jus manually add ‘?import_images=1’ so your url became http://example.com/wp-admin/?import_images=1
and hit Enter.
After some seconds you should see the posts created from images.
Be aware that this function cretae a post from all images you have updated. If you want exclude some images, you can take 2 ways:
-
look for the IDs of the images you want to exclude and add this 2 lines:
$exclude = array(12, 256, 587); // the ids you want to skip if ( in_array($image->ID, $exclude) ) continue;
before
if ( get_post_meta($image->ID, '_imported', true) ) continue;
-
Previous method is good if you want to exclude a little number of images, if you want to exclude more, you can register a custom taxonomy for the attachments and assign a particular term to images you want to skip (e.g. ‘skip’). (For these tasks a read here can help you). After that, Assuming you taxonomy is called ‘media-tag’ and you have added the ‘skip’ term to the images you want to skip, add this line at same place:
if ( has_term('skip', 'media-tag', $image->ID) ) continue;