How to select all images from a folder and display them in admin area?

This code works on my localhost, but when I install the plugin on live website, I have to do some changes. Is there a way to write something that will work on any WP website? The problem is path… Files are selected and displayed (I’ve created a shortcode for this function and I’m calling it on submenu page of Media that I created…) well, but I had to use str_replace and have to do that on every website for that specific path.

I’ve tried also with site_url() and then path to the folder, there is no error, but images are not displayed.

Images are uploaded with this plugin also in folder that this plugin creates, wp-content/uploads/onixion-images

Here is the function:

function folder_gallery__shortcode( $atts ) {
$a = shortcode_atts(
array (
‘folder’ => ”,
‘title’ => ”,
), $atts );

$folder = $a [ ‘folder’ ];

// bad folder
if ( empty( $folder ) || ! is_readable(ABSPATH . $folder) ) {
return ‘No Valid Folder Selected’;
}

// allow filtering of the filetypes
$filetypes = apply_filters( ‘folder_gallery_shortcode__filetypes’,
array ( ‘png’, ‘jpg’, ‘jpeg’, ‘gif’ ) );

// glob
$filetypes = empty( $filetypes ) ? ‘png,jpg,jpeg,gif’ : implode(
‘,’, $filetypes );
$files = glob( untrailingslashit( ABSPATH . $folder ) . “/*.{”
. $filetypes . “}”, GLOB_BRACE );
//$onixion_files = glob( site_url() . “/wp-
// content/uploads/onixion-images/*.{” . $filetypes . “}”, GLOB_BRACE
);
//get_home_path() . ‘/uploads/onixion-images
//site_url()

$gallery_images = array ();
foreach ( $files as $file ) {
if ( $file === __FILE__ ) {
continue;
}

/*
$filetype = wp_check_filetype( $file );
$ext = $filetype[ ‘ext’ ];
$type = $filetype[ ‘type’ ];
$proper_filename = $filetype[ ‘proper_filename’ ];
*/

// replace the filepath
$onixion_uploaded_image = str_replace( trailingslashit( ABSPATH
), trailingslashit( ‘WP_SITEURL’ ), $file );
$onixion_uploaded_image= str_replace(“wp-admin/WP_SITEURL/”,
“”, $file);
$onixion_uploaded_image=
str_replace(“/Users/mac/Desktop/onixion-test-site”, “”, $file);

$gallery_images[] = $onixion_uploaded_image;

}

// construct the gallery
$output = empty( $a[ ‘title’ ] ) ? ” : ‘<h2>’ . $a[ ‘title’ ] .
‘</h2>’;
$output .= ‘<div class=”container-fluid”><div class=”row”>’;

// Loop through each image in each gallery
foreach ( $gallery_images as $image_url ) {
$output .= ‘<div class=”col-sm-1″>’ . ‘<a href=” ‘ . $image_url
. ‘ ” target=”_blank”><img class=”img-responsive img-thumbnail” src=”‘
. $image_url . ‘”>’ . ‘</div>’;
}
$output .= ‘</div></div>’;

// allow filtering of the output
$gallery = apply_filters( ‘folder_gallery_shortcode__gallery’,
$output, $gallery_images );

return $gallery;
}

Read more here:: How to select all images from a folder and display them in admin area?

Leave a Reply

Your email address will not be published. Required fields are marked *