将上次修改时间作为版本添加到css和js

时间:2017-06-10 作者:Stickers

我能够将上次修改的文件作为版本添加到css和js文件中。如你所见,我不得不反复添加filemtime(get_theme_file_path(\'...\')) 每次添加新链接时。

function _enqueue_scripts() {
    wp_enqueue_style(\'_base\', get_theme_file_uri(\'/assets/css/base.css\'), array(), filemtime(get_theme_file_path(\'/assets/css/base.css\')));
    wp_enqueue_script(\'_base\', get_theme_file_uri(\'/assets/js/base.js\'), array(), filemtime(get_theme_file_path(\'/assets/js/base.js\')));
}
add_action(\'wp_enqueue_scripts\', \'_enqueue_scripts\');
有没有一种方法可以对其使用自定义筛选器,而不是每次手动添加该行?

类似于下面的函数(用于删除版本号),但我想添加版本号。

function _remove_script_version($src) {
    return $src ? esc_url(remove_query_arg(\'ver\', $src)) : false;
}
add_filter(\'style_loader_src\', \'_remove_script_version\', 15, 1);
add_filter(\'script_loader_src\', \'_remove_script_version\', 15, 1);

5 个回复
最合适的回答,由SO网友:inarilo 整理而成

你可以使用add_query_arg() 但是,您每次都必须解析uri,我宁愿为wp\\u enqueue\\u脚本/样式创建一个包装函数:

function my_enqueuer($my_handle, $relpath, $type=\'script\', $my_deps=array()) {
    $uri = get_theme_file_uri($relpath);
    $vsn = filemtime(get_theme_file_path($relpath));
    if($type == \'script\') wp_enqueue_script($my_handle, $uri, $my_deps, $vsn);
    else if($type == \'style\') wp_enqueue_style($my_handle, $uri, $my_deps, $vsn);      
}
将其添加到函数文件中,然后替换,例如。

wp_enqueue_script(\'_base\', get_theme_file_uri(\'/assets/js/base.js\'), array(), filemtime(get_theme_file_path(\'/assets/js/base.js\')));
电话:

my_enqueuer(\'_base\', \'/assets/js/base.js\');
并代替,例如。

wp_enqueue_style(\'_base\', get_theme_file_uri(\'/assets/css/base.css\'), array(), filemtime(get_theme_file_path(\'/assets/css/base.css\')));
电话:

my_enqueuer(\'_base\', \'/assets/css/base.css\', \'style\');
需要时,可以将依赖项数组作为最后一个参数传递。对于脚本,如果传递依赖项数组,则还必须传递第三个参数“script”,即使我已将其设置为默认值。

SO网友:Mr. HK

我以前使用YYYYMMDD作为排队文件的版本号,这很好,但当它一天更改多次时会导致问题,这意味着在更改文件时必须记住更新版本号。排队的示例可能如下所示:

<?php wp_enqueue_style( \'child-theme\', get_stylesheet_directory_uri() . \'/css/styles.css\', array(), \'20150731\' ); ?>
我修改后的方法首先为CSS/JS文件的路径创建一个变量,然后在版本号中使用filemtime,而不是YYYYMMDD:

<?php
$themecsspath = get_stylesheet_directory() . \'/css/styles.css\';
wp_enqueue_style(
    \'child-theme\',
    get_stylesheet_directory_uri() . \'/css/styles.css\',
    array(),
    filemtime( $themecsspath )
);
?>
现在,我将不使用包含WordPress版本号的排队文件,如下所示:

<link rel=\'stylesheet\' id=\'child-theme-css\'  href=\'http://example.com/wp-content/themes/child/css/styles.css?ver=4.3.1\' type=\'text/css\' media=\'all\' />
它们看起来像这样:

<link rel=\'stylesheet\' id=\'child-theme-css\'  href=\'http://example.com/wp-content/themes/child/css/styles.css?ver=1447781986\' type=\'text/css\' media=\'all\' />

SO网友:Michael Ecklund

此答案改编自@CGodo\'s solution.

我在原始代码中遇到了致命错误。我已经测试了这段代码,它实现了我认为原始答案的目的。

/**
 * Replaces query version in registered scripts or styles with file modified time
 *
 * @param $src
 *
 * @return string
 */
function add_modified_time( $src ) {

    $clean_src = remove_query_arg( \'ver\', $src );
    $path      = wp_parse_url( $src, PHP_URL_PATH );

    if ( $modified_time = @filemtime( untrailingslashit( ABSPATH ) . $path ) ) {
        $src = add_query_arg( \'ver\', $modified_time, $clean_src );
    } else {
        $src = add_query_arg( \'ver\', time(), $clean_src );
    }

    return $src;

}

add_filter( \'style_loader_src\', \'add_modified_time\', 99999999, 1 );
add_filter( \'script_loader_src\', \'add_modified_time\', 99999999, 1 );

SO网友:CGodo

如果出于某种原因有人需要它,这些挂钩将在所有Wordpress脚本和样式上添加修改后的时间版本,但从PHP加载的脚本和样式除外。

它使用WP\\u脚本和WP\\u样式单例的原因是这些实例已经计算了base\\u url。

/**
 * Replaces query version in registered scripts or styles with file modified time
 * @param string $src Source url
 * @param string $baseUrl Site base url
 * @return string
 */
function put_modified_time_version($src, $baseUrl)
{
    // Only work with objects from baseUrl
    if ($src && strpos($src, $baseUrl) === 0) {
        // Remove any version
        $newSrc = remove_query_arg(\'ver\', $src);
        // Get path after base_url
        $path = substr($newSrc, strlen($baseUrl));
        $path = wp_parse_url($path, PHP_URL_PATH);
        // Apply modified time version if exists
        if ($mtime = @filemtime(untrailingslashit(ABSPATH) . $path)) {
            $src = add_query_arg(\'ver\', $mtime, $newSrc);
        }
    }
    return $src;
}

/**
 * Filters style sources to put file modified time as query string
 * @param $src
 * @return string
 */
function modified_time_version_style($src) {
    // base_url from WP_Versions is already in memory
    return ($src) ? put_modified_time_version($src, wp_styles()->base_url) : $src;
}

/**
 * Filters script sources to put file modified time as query string
 * @param $src
 * @return string
 */
function modified_time_version_script($src) {
    // base_url from WP_Styles is already in memory
    return ($src) ? put_modified_time_version($src, wp_scripts()->base_url) : $src;
}

add_filter(\'style_loader_src\', \'modified_time_version_style\', 15, 1);
add_filter(\'script_loader_src\', \'modified_time_version_script\', 15, 1);

SO网友:user1030151

我刚刚为我的插件类编写了两个方法,这使得注册/排队脚本和样式非常容易。当然,根据需要,最后一次修改时间始终添加为版本参数。也许这会帮助别人

如何使用它们:

/**
 * For these examples we assume that your plugin assets are located in
 * wp-content/plugins/my-plugin/path/to/assets/
 */

// add your style
$this->registerAsset(\'path/to/assets/your-style.css\');

// add your script works exactly the same
$this->registerAsset(\'path/to/assets/your-script.js\');

// add script with dependency
$this->registerAsset(\'path/to/assets/script-with-dependencies.js\', [
    \'jquery\'
]);

// add script with internal dependency
$this->registerAsset(\'path/to/assets/script-with-dependencies.js\', [
    \'jquery\',
    $this->getAssetHandle(\'path/to/assets/your-script.js\')
]);

// for internal dependencies you can also pass the path of the dependency directly
$this->registerAsset(\'path/to/assets/script-with-dependencies.js\', [
    \'jquery\',
    \'path/to/assets/your-script.js\'
]);
还有一些选项,但只需查看有关所需源代码中的方法的文档即可:

class myPlugin
{
    public function __construct()
    {
    }
    
    /**
     * Registers and enqueues a script or style
     * 
     * @param   STRING        $path          The path of the file you want to register or enqueue (relative to your plugin folder).
     * @param   ARRAY         $dependencies  The dependencies as you know from wp_enqueue_script, but allows also paths of other assets that were registered with this method.
     * @param   BOOLEAN       $enqueue       If FALSE it will only be registered, otherwise it will also be enqueued.
     * @param   STRING|NULL   $type          Type of the asset. Allowed types are \'script\' and \'style\'. If it is NULL, the type is automatically detected from the file extension.
     * @param   STRING        $media         To define \'media\' when adding CSS (Ignored for JS assets - JS assets always get TRUE for the in_footer parameter as this is usually the recommended way)
     * 
     * @return  BOOLEAN|NULL  When $enqueue is TRUE, the return value is always NULL. Otherwise TRUE on success, FALSE on failure.
     */
    public function registerAsset($path, $dependencies = [], $enqueue = true, $type = null, $media = \'all\')
    {
        $path = \'/\' . ltrim($path, \'/\');
        $pluginDirName = explode(DIRECTORY_SEPARATOR, ltrim(str_replace(realpath(WP_PLUGIN_DIR), \'\', realpath(__FILE__)), DIRECTORY_SEPARATOR), 2)[0];
        $pluginDir = realpath(WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $pluginDirName);

        if ($type === null) {
            $extensions = [\'js\' => \'script\', \'css\' => \'style\'];
            $extension = pathinfo($path, PATHINFO_EXTENSION);
            $type = isset($extensions[$extension]) ? $extensions[$extension] : null;
        }
        if (!in_array($type, [\'script\', \'style\']) || !file_exists($pluginDir . $path)) {
            return;
        }

        foreach ($dependencies as $index => $dependency) {
            if (preg_match(\'/\\.(js|css)$/\', $dependency) && file_exists($pluginDir . DIRECTORY_SEPARATOR . ltrim($dependency, \'\\\\/\'))) {
                $dependencies[$index] = $this->getAssetHandle($dependency);
            }
        }

        $func = \'wp_\' . ($enqueue ? \'enqueue\' : \'register\') . \'_\' . $type;
        return $func($this->getAssetHandle($path), plugins_url($pluginDirName . $path), $dependencies, filemtime($pluginDir . $path), $type === \'script\' ? true : $media);
    }

    /**
     * Gets the handle of an asset that registerAsset() uses automatically
     * 
     * @param   STRING        $path          The path that you used with registerAsset()
     * 
     * @return  STRING        The handle name of the asset
     */
    public function getAssetHandle($path)
    {
        $pluginDirName = explode(DIRECTORY_SEPARATOR, ltrim(str_replace(realpath(WP_PLUGIN_DIR), \'\', realpath(__FILE__)), DIRECTORY_SEPARATOR), 2)[0];
        return preg_replace(\'/[^a-zA-Z0-9]+/\', \'-\', $pluginDirName . \'-\' . $path);
    }
}

结束

相关推荐