1

I set up a webpack configuration, that uses the MiniCssExtractPlugin to compile my css into a single file into my public folder.

    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css'
    }),

The final file looks like this:

styles.f14f755f197392ce2228.css

I also use an index.php file, which just get's copied into the public folder.

My question now is:
How do I include my hashed CSS file inside my index.php file without altering the name on each build manually?
Is there some kind of helper function that gives me the name of the css file?

Thank you :)

2 Answers 2

2

I have a function in wordpress that reads hashed css/js. You just have to adapt it;)

function kodywig_matchFile($partOfName, $folder) {
  $handler = get_template_directory().'/assets/'.$folder;
  $openHandler = opendir($handler);
  while ($file = readdir($openHandler)) {
    if ($file !== '.' && $file !== '..') {
      if (preg_match("/^".$partOfName."\w+.(".$folder.")/i", $file, $name)) {
        return $name[0];
      }
    }
  }
  closedir($openHandler);
}

how to use it

echo '<link href="'. get_template_directory_uri() . '/assets/css/' . kodywig_matchFile('styles-', 'css') . '" rel="stylesheet">';
Sign up to request clarification or add additional context in comments.

7 Comments

Hi, thank you for the quick response, do you import the file in wordpress as shown or do you enqueue it?
Can you maybe give an example on how your stylesheet is named and placed in the folder?
Here you have the whole example docker-wordpress-xdebug. It's just a template, but it works;)
Okay, I tried it but it didn't work, my folder public has the subfolder assets/css like in your example, do I need to trigger functions php manually or is this done by wordpress?
Refreshing the site should download css/js, but if you have plugins, e.g. for file caching, you must disable them. In my example, everything works automatically, changes in php, css and js generate css/js and save automatically to the wordpress template and reload it and refresh the page preview. Well, unfortunately I can't help, there can be many reasons why it doesn't work for you. Without your code, I can only predict it;)
|
1

Based on the awesome help from @Grzegorz T's answer, I've done this function which currently using on my php app (not Wordpress):

  function get_asset($filename)
  {

    $dirName = dirname($filename); // if we have a file name like dir1/dir2/style.css
    $fileBaseName = pathinfo($filename, PATHINFO_FILENAME); // Just the file name
    $fileExt = pathinfo($filename, PATHINFO_EXTENSION); // Just the file extension
    // $assetType handles the asset folder inside the dist folder
    switch ($fileExt) {
      case 'js':
        $assetType = 'scripts'; // dir/scripts
        break;
      case 'png':
      case 'jpg':
      case 'gif':
      case 'ico':
        $assetType = 'images'; // dir/images
        break;
      default:
        $assetType = 'styles'; // dir/styles
    }

    // if the file is inside another folder inside "dist" folder
    if ($dirName != '.') {
      $handler = $_SERVER['DOCUMENT_ROOT'] . "/dist/$assetType/$dirName/";
      $externalHandler = $_SERVER['SERVER_NAME'] . "/dist/$assetType/$dirName/"; // for viewing it. e.g: http://example.com/dist/styles/style1/main.css
    } else {
      $handler = $_SERVER['DOCUMENT_ROOT'] . "/dist/$assetType/";
      $externalHandler = $_SERVER['SERVER_NAME'] . "/dist/$assetType/"; // for viewing it. e.g: http://example.com/dist/styles/main.css
    }

    $openHandler = opendir($handler);
    while ($file = readdir($openHandler)) {
      if ($file !== '.' && $file !== '..') {
        if (preg_match("/^" . $fileBaseName . "(.\w+)?." . $fileExt . "/i", $file, $name)) {
          return $externalHandler . $name[0];
        }
      }
    }
    closedir($openHandler);
  }

The benefits of this function:

  • You can use it to get css, js, or images, having a hash in the name or not.
  • You can use it even if the file inside nested folders of the dist folder...which webpack will build and bundle all your styles and scripts inside.

How to use

File structure example:

|-- dist
|    |--  images
|    |    |-- admin
|    |        |-- test
|    |            |-- no-user2.png
|    |--  styles
|    |    |--  style-en.210b2f23cdb14668c0f1.css
|    |--  scripts

Example 1: Hashed style

echo (get_asset('style-en.css'));

This gets:

website.local/dist/styles/style-en.210b2f23cdb14668c0f1.css

Example 2: Nested image

echo (get_asset('admin/test/no-user2.png'));

This gets:

example.local/dist/images/admin/test/no-user2.png


Updated Way 2:

I've just found another awesome way with Webpack, by using Webpack Assets Manifest plugin. This generates a JSON file that matches the original filename with the hashed version.

After generating the final JSON file, you can read the json file using PHP and call the needed files.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.