0

I would like to be able to get the URL of a html file that has been uploaded to a folder via FTP.

So if I go into a post in the admin back end of WordPress, I would like there to be a custom field with a file browser that would list the html files and subdirectories in: wp-content/uploads/articles/

Then when a file has been selected it will log the url of that file so it can be retrieved on the front end.

I've done countless searches on Google and here and can't seem to find the answer I'm looking for. Would just like to know if it can or cant't be done so I can plan accordingly.

Any insight would be greatly appreciated!

1 Answer 1

0

You can scan the directory for files with glob() then loop throw the results and list them in a admin modal (thickbox) or just show the list within a admin metabox in the post editor.

Here's a little snippet that i was playing with.

/**
 * Get HTML Article Files from uploads/articles
 * Support both .htm & .html ext.
 * 
 * @return array List of html article files with path & url.
 */
function wpse_384622_get_articles() {
    $uploads   = wp_upload_dir();
    $file_path = $uploads['basedir'] . '/articles/';
    $file_url  = $uploads['baseurl'] . '/articles/';
    $articles  = [];
    foreach ( glob( $file_path . '*.htm*' ) as $path ) {
        if ( is_readable( $path ) ) {
            $file_type = wp_check_filetype( $path );
            if ( 'text/html' === $file_type['type'] ) {
                $file_list[] = [
                    'path' => $path,
                    'url'  => str_replace( $file_path, $file_url, $path ),
                ];
            }
        }
    }
    
    return $articles;
}
8
  • Thanks for that, didn't think of using glob in the back end. Seems pretty straight forward but only the box shows up with nothing in it when adding into a metabox function. Mar 7, 2021 at 5:59
  • Have tested within wp-admin, and it was working well, you might need to debug a bit. Mar 7, 2021 at 6:01
  • Yes it's working now, just gotta get the checkboxes to save correctly... Mar 8, 2021 at 10:04
  • Another question, how would I modify this to list the html files in all subdirectories within /articles/ as per my original query? Mar 9, 2021 at 2:53
  • 1
    All good. Ended up using RecursiveDirectoryIterator Mar 18, 2021 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.