从文件名为 LIKE 的路径获取文件

问题描述 投票:0回答:1

我正在开发一个 WordPress,它利用 gulp 构建应用程序(scss、js)文件的前端。

在我的

functions.php
中,我正在使用 enqueue 加载我的 css 和 js,以便它们可以在编辑器中使用。

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 运行一个简单的

gulp
命令我可以执行上述操作,因为文件将被命名为
main.css
。但是,我遇到一个问题,当我使用
gulp --production
样式和 javascript 后缀为随机值。

例如我的 main.scss 将(一旦我运行上面的命令)变成

main-9acd4829.css
.

我的问题是,我怎样才能从文件名像

main<whatever>.css
.

的某个目录中获取文件

我试过使用诸如

之类的东西
get_theme_file_uri(glob('/dist/styles/main*.css'), __FILE__)

但是返回 null

php wordpress gulp enqueue
1个回答
1
投票

我猜你必须在不同的文件夹中检查自己,受 get_theme_file_uri 代码的启发,像这样(注意

glob
返回一个数组,而
get_theme_file_uri
接受一个字符串):

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__) );
    }
} );
© www.soinside.com 2019 - 2024. All rights reserved.