• Resolved antonop4u

    (@antonop4u)


    Hi, I’m trying to get the list of files of my custom theme /image/ directory. I’m using the WordPress function list_files() and I keep getting the error “undefined function”.
    the PHP scandir(), doesn’t work either.
    Here is the code I’m using:

    
    $dir_path = get_template_directory_uri() . '/images/bkgrds/';
    $bkgrds = list_files( $dir_path );
    

    what am I doing wrong?
    Does anyone have any alternative working method to get the list of files out of a directory?

Viewing 8 replies - 1 through 8 (of 8 total)
  • You should use get_template_directory() instead of get_template_directory_uri()

    
    $dir_path = get_template_directory() . '/images/bkgrds/';
    $bkgrds = list_files( $dir_path );
    
    Thread Starter antonop4u

    (@antonop4u)

    I just tried and I’ve got exactly the same error “Call to undefined function list_files()”.

    Are there any limitations on where this function can be used?

    I hope you are using this function in the theme?

    Thread Starter antonop4u

    (@antonop4u)

    Yes, of course.
    I made a test, and the error was generated because I called the function after the page headers were set in few words between the get_header(); and the get_footer();.
    Now I’m calling it before the get_header(); and the error has disappeared. But I still can’t get the list of files inside the directory, and that directory has 39 jpg files inside.
    Any Idea?

    • This reply was modified 4 years, 10 months ago by antonop4u.

    Can you show your codes through https://pastebin.com/

    • This reply was modified 4 years, 10 months ago by Jogesh.
    Thread Starter antonop4u

    (@antonop4u)

    Forget what wrote above the error still exists even before the get_header();, I made a mistake I set the code inside an area where it wasn’t executed, that why the error disappeared.

    Dion

    (@diondesigns)

    The list_files() function is in wp-admin/includes/file.php, which is not loaded on the frontend. If you want to use list_files(), you’ll need to include that file in your code.

    Alternately, you could use a native PHP function:

    $dir_path = get_template_directory() . '/images/bkgrds/*';
    $bkgrds = glob($dir_path);

    The glob() function has many options to tailor the output to your needs. Docs:

    https://www.php.net/manual/en/function.glob.php

    Thread Starter antonop4u

    (@antonop4u)

    Thank you very much! very useful.

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘list_files() => error undefined function’ is closed to new replies.