get all the images from a folder in php

前端 未结 9 2236
南方客
南方客 2020-12-04 14:37

I am using WordPress. I have an image folder like mytheme/images/myimages.

I want to retrieve all the images name from the folder myimages<

9条回答
  •  無奈伤痛
    2020-12-04 15:19

    This answer is specific for WordPress:

    $base_dir = trailingslashit( get_stylesheet_directory() );
    $base_url = trailingslashit( get_stylesheet_directory_uri() );
    
    $media_dir = $base_dir . 'yourfolder/images/';
    $media_url = $hase_url . 'yourfolder/images/';
    
    $image_paths = glob( $media_dir . '*.jpg' );
    $image_names = array();
    $image_urls = array();
    
    foreach ( $image_paths as $image ) {
        $image_names[] = str_replace( $media_dir, '', $image );
        $image_urls[] = str_replace( $media_dir, $media_url, $image );
    }
    
    // --- You now have:
    
    // $image_paths ... list of absolute file paths 
    // e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
    
    // $image_urls ... list of absolute file URLs 
    // e.g. http://example.com/wp-content/uploads/yourfolder/images/sample.jpg
    
    // $image_names ... list of filenames only
    // e.g. sample.jpg
    

    Here are some other settings that will give you images from other places than the child theme. Just replace the first 2 lines in above code with the version you need:

    From Uploads directory:

    // e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
    $upload_path = wp_upload_dir();
    $base_dir = trailingslashit( $upload_path['basedir'] );
    $base_url = trailingslashit( $upload_path['baseurl'] );
    

    From Parent-Theme

    // e.g. /path/to/wordpress/wp-content/themes/parent-theme/yourfolder/images/sample.jpg
    $base_dir = trailingslashit( get_template_directory() );
    $base_url = trailingslashit( get_template_directory_uri() );
    

    From Child-Theme

    // e.g. /path/to/wordpress/wp-content/themes/child-theme/yourfolder/images/sample.jpg
    $base_dir = trailingslashit( get_stylesheet_directory() );
    $base_url = trailingslashit( get_stylesheet_directory_uri() );
    

提交回复
热议问题