0

I have written a funtion to get post image attachments, is there any way of ordering these images such that the first is always the post_thumbnail?

Code below

Thanks

John

function oliver_single_gallery_thumbs() {

global $post;

$args = array(
    'post_parent'    => $post->ID,          // For the current post
    'post_type'      => 'attachment',       // Get all post attachments
    'post_mime_type' => 'image',            // Only grab images
    'order'          => 'ASC',              // List in ascending order
    'orderby'        => 'menu_order',       // List them in their menu order
    'numberposts'    => -1,                 // Show all attachments
    'post_status'    => null,               // For any post status
);

$attachments = get_posts($args);
    if ($attachments) { 
        $count = 0;
        $the_thumbs = '<ul id="single-thumbs">';
        foreach ($attachments as $attachment) {
            $ze_count = $count+1;
            $the_thumbs .= '<li id="single-thumb-'.$ze_count.'">';
                if ($count==0) {
                    $thumb_attr = array(
                        'class' => "image-radius selected",
                    );
                } else {
                    $thumb_attr = array(
                        'class' => "image-radius",
                    );
                }
                $the_thumbs .= wp_get_attachment_image($attachment->ID, 'single-thumb', false, $thumb_attr);
            $the_thumbs .= '</li>'."\n";
            $count = $count + 1;
        }
        $the_thumbs .= '</ul>';
    }
    echo $the_thumbs;
}

1 Answer 1

2

First, exclude the featured image (= post thumbnail) from the query, then set up the posts array as combination of the featured image and the other images.

Put this directly below $args = ... and above $attachments = ...:

if (has_post_thumbnail($post->ID)) {
    $featured_image = get_post_thumbnail_id($post->ID);
    $args['exclude'] = $featured_image;
    $attachments = array(get_post($featured_image)) + get_posts($args);
} else
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.