Skip to content

Commit a40c559

Browse files
authored
feat: add filter to printPublicPath
* Add filter to printPublicPath This filter makes it possible to set publicPath to a custom URL e.g. a CDN * Actions and Filters section added to Readme.md
1 parent 8a5604f commit a40c559

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

README.md

+45
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,48 @@ Always require the latest version of `Wpackio\Enqueue`. The autoloader is set
135135
to load only one instance and will not conflict with existing class.
136136

137137
However, if you want to load conflict free, kindly use [Strauss](https://github.com/BrianHenryIE/strauss).
138+
139+
## Actions and Filters
140+
141+
### Filter `wpackio_print_public_path`
142+
143+
Accepts 3 parameters:
144+
145+
- `$publichPathUrl` The URL that is used for the publicPath
146+
- `$appName` Application Name
147+
- `$outputPath` Output path relative to the root of this plugin/theme.
148+
149+
150+
Using this you can dynamically change the public path that is used for code splitting.
151+
This can be used to change the public path to a CDN.
152+
153+
#### Example Code to replace all wpack.io public path with a cdn url
154+
155+
```php
156+
add_filter( 'wpackio_print_public_path', 'set_public_path_to_cdn' );
157+
158+
function set_public_path_to_cdn( $publichPathUrl ) {
159+
$home_url = get_home_url(); // WordPress home url
160+
$cdn_url = 'https://cdn.example.com'; // CDN url
161+
162+
// replace wordpress home url with cdn url
163+
return str_replace($home_url, $cdn_url, $publichPathUrl);
164+
}
165+
```
166+
#### Example Code to the change the public path url only for a specific instance of wpack.io
167+
168+
```php
169+
add_filter( 'wpackio_print_public_path', 'set_public_path_to_cdn', 10, 2 );
170+
171+
function set_public_path_to_cdn( $publichPathUrl, $appName ) {
172+
173+
// check for our plugin
174+
if( 'myPlugin' !== $appName ) return $publichPathUrl;
175+
176+
$home_url = get_home_url(); // WordPress home url
177+
$cdn_url = 'https://cdn.example.com'; // CDN url
178+
179+
// replace WordPress home url with cdn url
180+
return str_replace($home_url, $cdn_url, $publichPathUrl);
181+
}
182+
```

inc/Enqueue.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ private function sanitize_path( $path ) {
143143
* and dynamic imports possible.
144144
*/
145145
public function printPublicPath() {
146-
$publicPath = $this->getUrl( '' );
146+
$publicPath = apply_filters( 'wpackio_print_public_path', $this->getUrl( '' ), $this->appName, $this->outputPath );
147147
$jsCode = 'window.__wpackIo' . $this->sanitize_path( $this->appName . $this->outputPath ) . '=\'' . esc_js( $publicPath ) . '\';';
148148
echo '<script type="text/javascript">/* wpack.io publicPath */' . $jsCode . '</script>';
149149
}

0 commit comments

Comments
 (0)