我正在开发一个 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__) ); } );
运行一个简单的 gulp
命令我可以执行上述操作,因为该文件将被命名为 main.css
。但是,我面临一个问题,当我使用 gulp --product
时,样式和 javascript 会带有随机值后缀。
例如,我的 main.scss 将(一旦我运行上述命令)变成 main-9acd4829.css
。
我的问题是,如何从文件名类似于 main<whatever>.css
的某个目录获取文件。
我尝试过使用诸如
之类的东西get_theme_file_uri(glob('/dist/styles/main*.css'), __FILE__)
但是返回 null
P粉8850351142024-04-04 10:35:14
我想你必须在不同的文件夹中检查自己,灵感来自 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__) ); } } );