根據部分文件名匹配從指定路徑獲取文件
P粉194919082
P粉194919082 2024-04-03 14:50:46
0
1
412

我正在開發一個 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粉194919082
P粉194919082

全部回覆(1)
P粉885035114

我想你必須在不同的資料夾中檢查自己,靈感來自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__) );
    }
} );
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!