Skip to content

Magento 1.9 sorting media gallery images with base image on first page

From a product I want to get all the images it has in the gallery and sort them so that the main/base image of the product is first in the list. Firstly, I have a problem because I can’t get the main/basic image from the list and secondly, how can I rearrange the rest of the images.

I tried to get the main/basic image in the following way:

foreach ($data["media_gallery"]["images"] as $image) {
    if ($image['file'] === $this->product->getImage()) {
        //
    } else {
        //
    }
}

The problem is that if you have several images and you don’t have the main/base image marked as the first in the list, according to the code mentioned above, it doesn’t return the right image, but always returns the first one in the list as the header/base.

Can anybody help me how to first get image and then how to properly sort them.

Thank you