Home  >  Q&A  >  body text

Get files from specified path based on partial file name matching

I'm developing a WordPress that utilizes gulp to build the front-end of the application (scss, js) files.

In my functions.php I use enqueue to load my css and js so that they can be used in the editor.

add_action( 'enqueue_block_editor_assets', function() {
   wp_enqueue_style( 'editor-styling', get_theme_file_uri( '/dist/styles/main.css', __FILE__) );
   wp_enqueue_script( 'editor-scripts', get_theme_file_uri( '/dist/scripts/main.js', __FILE__) );

} );

Running a simple gulp command I can do the above because the file will be named main.css. However, I'm facing an issue, when I use gulp --product, the styles and javascript are suffixed with random values.

For example, my main.scss will (once I run the above command) become main-9acd4829.css.

My question is, how to get a file from a directory with a file name similar to main<whatever>.css.

I have tried using something like

get_theme_file_uri(glob('/dist/styles/main*.css'), __FILE__)

But returns null

P粉194919082P粉194919082172 days ago414

reply all(1)I'll reply

  • P粉885035114

    P粉8850351142024-04-04 10:35:14

    I think you have to check yourself in a different folder, code inspired by get_theme_file_uri, something like this (note that glob returns an array, and get_theme_file_uri accepts a string):

    add_action( 'enqueue_block_editor_assets', function() {
        $style_file = glob(get_stylesheet_directory() . '/dist/styles/main*.css');
        if(!$style_file || !count($style_file)){
            $style_file = glob(get_template_directory_uri() . '/dist/styles/main*.css');
        }
        //NOTE: you can use foreach if your glob returns multiple files and this is what you want
        //NOTE2: in theory you could skip the use of get_theme_file_uri here because you already tested in which folder it is, this is just an example
        if($style_file && count($style_file)){
            wp_enqueue_style( 'editor-styling', get_theme_file_uri( '/dist/styles/' . $style_file[0], __FILE__) );
        }
        
        $script_file = glob(get_stylesheet_directory() . '/dist/scripts/main*.js');
        if(!$script_file || !count($script_file)){
            $script_file = glob(get_template_directory_uri() . '/dist/scripts/main*.js');
        }
        //NOTE: you can use foreach if your glob returns multiple files and this is what you want
        //NOTE2: in theory you could skip the use of get_theme_file_uri here because you already tested in which folder it is, this is just an example
        if($script_file && count($script_file)){
            wp_enqueue_script( 'editor-scripts', get_theme_file_uri( '/dist/scripts/' . $script_file[0], __FILE__) );
        }
    } );

    reply
    0
  • Cancelreply