Pilot-in / PiloPress

The most advanced WordPress Page Builder using Advanced Custom Fields & TailwindCSS
https://www.pilopress.com
63 stars 11 forks source link

Auto-invalidate cache for Pilo'Press layouts scripts using `filemtime` #233

Closed DamChtlv closed 1 year ago

DamChtlv commented 1 year ago

Is your feature request related to a problem? Please describe. Sometimes, users see an old version of layouts scripts because they have some local cache of it, and they think the issue they had related to these files still exists.

Describe the solution you'd like (proof of concept)

// Use file modification date to invalidate Pilo'Press scripts files
add_filter( 'script_loader_src', 'invalidate_pilopress_scripts_cache', 10 );
function invalidate_pilopress_scripts_cache( $url ) {

    // Target only Pilo'Press layouts scripts
    if ( strpos( $url, 'pilopress/layouts' ) === false ) {
        return $url;
    }

    // Remove potential "?ver" string in url
    $url = remove_query_arg( 'ver', $url );

    // Replace url structure by a path
    $script = str_replace( home_url(), '', $url );

    // Use pathinfo to get filename
    $script      = pathinfo( $script );
    $script_name = acf_maybe_get( $script, 'filename' );
    if ( !is_array( $script ) || !$script_name ) {
        return $url;
    }

    // Return script url including file modification date timestamp as "?ver" string
    $url = PIP_THEME_LAYOUTS_URL .
          "$script_name/$script_name.js?ver=" .
          filemtime( PIP_THEME_LAYOUTS_PATH . "$script_name/$script_name.js" );

    return $url;
}

Results:

image