我正在開發一個 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__) ); } } );