How can I autopopulate titles in the media library?

I have hundreds of images in my media library, most have which have no titles.
In the media library, the “(no title)” message is displayed along these images.

Since I generally have one image per post, I would like to auto-populate the library titles, by grabbing the associated post name. I don’t mind if I overwrite some existing titles.

Does anyone know of a hack that will do this?

I found some plugins, like ‘Media Rename’ and ‘Rename Media’ and ‘SEO friendly images’ but they are usually for renaming the actual image files, or for creating HTML title tags directly in the HTML (on the fly).

I want to create titles within the WordPress media library, so that I don’t see the (no title) message. This title data will also help me to search for images in the library — although, for anyone with the same issue, I did find a plugin called ‘Media Search’ that enables searching images by associated posts: http://wordpress.org/extend/plugins/media-library-search/

1 Answer
1

If you can do SQL manually then try:

UPDATE wp_posts p INNER JOIN wp_posts q ON p.post_type="attachment" AND p.post_mime_type LIKE 'image/%' AND (p.post_title IS NULL OR LENGTH(p.post_title) = 0) AND p.post_parent = q.ID SET p.post_title = q.post_title;

If you need a PHP function then try:

function set_image_without_title_to_post_title() {
  global $wpdb; 

  $sql = sprintf( "UPDATE %s p INNER JOIN %s q "
    . "ON p.post_type="attachment" AND p.post_mime_type LIKE 'image/%%' " 
    . "AND (p.post_title IS NULL OR LENGTH(p.post_title) = 0) "
    . "AND p.post_parent = q.ID "
    . "SET p.post_title = q.post_title",
    $wpdb->posts, $wpdb->posts );

  $wpdb->get_results( $sql, ARRAY_A );
}

WARNING: As this will make massive changes to your database I would do a backup first!
I did run a small test and it appears to be correct but USE AT YOUR OWN RISK!

Leave a Comment