select post preview image from nextgen gallery

EDIT: function and plugin below work, but are not necessary

Last version of Nexgen galley as a function to set featured images:

enter image description here


EDIT 2: My plugin

Just for the exercise, I used the function originally published to create a plugin with the functionality required by OP.

The code is in a Gist.


First of all, in all the posts you want show the preview image, you have to add a custom field, named ‘gallery_id’:

Please note that you are not required to actually put a NexGEN gallery into the post, you can use an image from a gallery even if no gallery is attached to post, just put the gallery_id custom field in the post and you are done.

After that, in your functions.php put:

function nextgen_preview_img( $post = null, $linkto = 'post') {
  if ( intval($post) ) $postid = $post;
  if ( empty($post) ) global $post;
  if ( is_object($post) && ! isset($postid) ) $postid = $post->ID;
  if ( ! intval($postid) ) return;
  $gallery_id = (int)get_post_meta($postid, 'gallery_id', true);
  if (! intval($gallery_id) ) return;
  global $wpdb;
  $galleries = $wpdb->prefix . 'ngg_gallery';
  $images = $wpdb->prefix . 'ngg_pictures';
  $gallery = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $galleries WHERE gid = %d", $gallery_id) );
  if ( $gallery ) {
    if ( intval($gallery->previewpic) ) {
      $thumb = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $images WHERE pid = %d", $gallery->previewpic) );
    } else {
      $thumb = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $images WHERE galleryid = %d ORDER BY sortorder ASC LIMIT 1", $gallery_id) );
    }
    if ( $thumb ) {
      $meta = (array) maybe_unserialize($thumb->meta_data);
      $file = ( isset($meta['thumbnail']['filename']) ) ? 'thumbs/' . $meta['thumbnail']['filename'] : $thumb->filename;
    }
    $url = site_url( trailingslashit($gallery->path) . $file );
    $img = sprintf('<img src="https://wordpress.stackexchange.com/questions/108093/%s" class="nextegen_preview_img" alt="https://wordpress.stackexchange.com/questions/108093/%s" />', esc_url($url), $thumb->alttext );
    $link = $linkto == 'post' ? get_permalink($post) : site_url( trailingslashit($gallery->path) . $thumb->filename );
    printf('<a href="https://wordpress.stackexchange.com/questions/108093/%s" class="nextegen_preview_a">%s</a>', $link, $img);
  }
}

This function get the preview image from the NexGEN gallery identified by the custom field ‘gallery_id’ attached to a post.

A gallery have some posts, so, how does the function select the image to display? It’s easy: if in the NexGEN gallery setting you have selected a ‘Preview image’ it will be used, otherwise is used the first image, according to the sort order you set in NexGEN settings.