Frontend Assets¶
Two complementary classes handle asset loading. Assets is suited for build tools that output hashed filenames; Manifest is suited for Vite-style manifest files.
Assets¶
Barberklingen\BasePlugin\Frontend\Assets
Scans a build directory for CSS and JS files, handles version hashing, and enqueues or prints them.
use Barberklingen\BasePlugin\Frontend\Assets;
$assets = new Assets(
prefix: 'my-theme', // handle prefix for wp_enqueue_*
dir: get_template_directory() . '/dist',
dir_uri: get_template_directory_uri() . '/dist',
sub_folder: 'assets' // optional sub-folder within dir
);
Enqueue a specific file¶
// Returns the public URI for a file
$uri = $assets->get_uri('js', 'app'); // e.g. /dist/app.abc123.js
$uri = $assets->get_uri('css', 'main'); // e.g. /dist/main.abc123.css
// Print a <script> or <link> tag directly
$assets->print_script_import('js', 'app', ['defer' => true]);
Auto-enqueue all files¶
$assets->autoload('js', [
'app' => [
'condition' => is_singular(), // optional: skip if false
'data' => [ // optional: localize the script
'name' => 'MyAppData',
'variables' => ['ajaxUrl' => admin_url('admin-ajax.php')],
],
],
]);
Filters:
assets-autoloader/autoload-file— fired before enqueuing; returnfalseto skipassets-autoloader/print-file— fired before printing inline; returnfalseto skip
Deduplication¶
When multiple hashed versions of the same base file exist in the directory, Assets keeps only the newest (sorted by mtime descending) and discards the rest.
Manifest¶
Barberklingen\BasePlugin\Frontend\Manifest
Reads a Vite-generated manifest.json to resolve file paths and hashed names.
use Barberklingen\BasePlugin\Frontend\Manifest;
$manifest = new Manifest(
manifest_path: get_template_directory() . '/dist/.vite/manifest.json',
files_prefix: get_template_directory() . '/dist',
files_uri: get_template_directory_uri() . '/dist'
);
// Enqueue a JS entry point
$manifest->js('src/main.ts', condition: true, dependencies: [], data: [
'name' => 'MyApp',
'variables' => ['nonce' => wp_create_nonce('my-action')],
]);
// Enqueue a CSS file
$manifest->css('src/style.css', condition: true, dependencies: []);
Path replacements¶
Localisation filter¶
Script localisation data can be extended via a filter:
add_filter('manifest-autoloader/js/localized/{handle}', function (array $data): array {
$data['extraKey'] = 'value';
return $data;
});
GlobalAppJS¶
Barberklingen\BasePlugin\Frontend\GlobalAppJS
Injects a global JavaScript object into the page with site-wide configuration data (URLs, nonces, locale, etc.) that frontend scripts need.
Template¶
Barberklingen\BasePlugin\Frontend\Template
Simple PHP template renderer. Passes variables into scope and returns the rendered output.