Javascript 如何在wordpress站点中使用PHP查找哈希bundle.js文件并将适当的文件名插入脚本标记?
所以,直到今天我才编写过php,我正试图在wordpress站点上实现一个缓存破坏系统,该站点中有一些React组件。因此在Javascript 如何在wordpress站点中使用PHP查找哈希bundle.js文件并将适当的文件名插入脚本标记?,javascript,php,wordpress,webpack,Javascript,Php,Wordpress,Webpack,所以,直到今天我才编写过php,我正试图在wordpress站点上实现一个缓存破坏系统,该站点中有一些React组件。因此在footer home.php文件中,我有以下内容: </div> <?php // close #app ?> </main> <div class="container footer"> <div class="row"> <div class="col-sm
footer home.php
文件中,我有以下内容:
</div> <?php // close #app ?>
</main>
<div class="container footer">
<div class="row">
<div class="col-sm-12">
<div id="instagram"></div>
</div>
</div>
<?php get_footer('shared') ?>
</div>
</div><?php //close container ?>
<?php
function grab_hashed_bundle_script() {
$path = '/client/';
$fileName = null;
$dirJS = new DirectoryIterator($path);
foreach ($dirJS as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) === 'js') {
$fileName = basename($file);
break;
}
}
return $fileName;
}
$bundle_js = grab_hashed_bundle_script();
?>
<script src="/client/<?php echo $bundle_js ?>"></script>
<?php wp_footer(); ?>
</body>
</html>
将js文件的请求更改为在文件名中使用查询参数而不是随机字符串
见下文。浏览器不应使用查询字符串对其进行缓存。这是我的一位同事提出的解决方案:
functions.php的内部:
/**
* Grab Hashed Bundle Files
*/
function enqueue_hashed_bundle_files() {
// soooo gross. would love to know of a cleaner way.
$build_dir = get_theme_root() . '/../../../client/build/';
$all_files = scandir($build_dir);
$css_files = array();
$js_files = array();
foreach( $all_files as $file ){
$pathinfo = pathinfo($file);
switch( $pathinfo['extension'] ){
case 'js':
array_push($js_files, $file);
break;
case 'css':
array_push($css_files, $file);
break;
default:
break;
}
}
// now that we have the filenames, we can access them directly with the
// absolute url
$base_url = get_option('siteurl') . '/client/';
wp_enqueue_script( 'bundlejs', $base_url . $js_files[0], array(), null, true );
wp_enqueue_style( 'bundlecss', $base_url . $css_files[0], array(), null );
}
我们通常只附加一个时间戳,如果你建议的解决方案是破坏缓存,那么就这么说,并提供一些代码示例,提供仅链接的答案很可能会引起版主的注意,可能与我试图做的完全不同。我试图在wordpress模板中处理这个问题,而不是在服务器文件系统中。您无法在客户端创建相同的随机6位数字。您必须更改服务器上的JS文件。有两种技术,例如。否则,您可以使用@James的答案来避免缓存。无论如何,您必须停止在文件名中添加随机数。这根本没用。@Buaban在下面看到我的答案。这绝对是可能的,对文件进行散列确实有帮助。我使用webpack在文件名中添加一个散列,然后使用Wordpress“wp_enqueue_script/style”获取并插入它。@JeremyGunter谢谢。我懂了。我误解了你的问题,我以为你想做客户端。