Envira Gallery Documentation

Documentation, Reference Materials and Tutorials for Envira Gallery

Sort Images by Uploaded Date

To sort Envira Gallery images by uploaded date:

  1. Add the following code to a new file at wp-content/plugins/envira-gallery-sort-uploaded.php
  2. <?php
    /**
    * Plugin Name: Envira Gallery - Sort Images by Latest Uploaded
    * Plugin URI: https://enviragallery.com
    * Version: 1.0
    * Author: Envira Gallery Team
    * Author URI: https://enviragallery.com
    * Description: Sorts Envira Gallery images by last uploaded.
    */
    /**
    * Sort images in an Envira Gallery by descending order
    * 
    * @since 1.0
    *
    * @param array  $data           Gallery config
    * @param int    $gallery_id     Gallery ID
    * @return array                 Gallery config
    */
    function envira_gallery_sort_images( $data, $gallery_id ) {
        // Iterate through gallery images, getting attachment data and creation date
        $attachments = array();
        $images = $data['gallery'];
        foreach ( $images as $attachment_id => $image ) {
            // Get attachment's date and time
            $attachment = get_post( $attachment_id );
            $date_time = strtotime( $attachment->post_date );
            // Add to new attachments array
            $attachments[ $date_time ] = $attachment_id;
        }
        // Sort attachments by key, oldest to newest
        asort( $attachments );
        $attachments = array_reverse( $attachments, true );
        // Rebuild images array
        unset( $data['gallery'] );
        foreach ( $attachments as $when => $attachment_id ) {
            $data['gallery'][ $attachment_id ] = $images[ $attachment_id ];
        }
    	return $data;
    }
    add_filter( 'envira_gallery_pre_data', 'envira_gallery_sort_images', 10, 2 );
    
  3. Navigate to the WordPress admin » Plugins and activate the Envira Gallery – Sort Images by Latest Uploaded plugin.