How do I fix this site speed recommendation with wordpress to remove query strings from static resources.
I have some Resources with a "?x54532" on the final of the link including images, js, css....
des/css/dashicons.min.css?x54532'
wp-includes/css/admin-bar.min.css?x54532
wp-content/uploads/2017/12/favicon.png?x54532"
I have 131 links with that query string"?x54532"
The advice "Remove query strings from static resources" is no longer relevant.
The advice originally came from Google PageSpeed but they dropped the recommendation in 2014. By that point, GTMetrix and Pingdom had already adopted all the PageSpeed recommendations and they've not yet updated their testing criteria to match the new PageSpeed recommendations.
You can go direct to Google PageSpeed to test your website here:
https://developers.google.com/speed/pagespeed/insights/
You will notice that "Remove query strings from static resources" is not a PageSpeed recommendation. The reason Google dropped it is because proxy servers like Squid have been caching static resources with query strings for about a decade already.
There are other good reasons why you should ignore the query string advice, not least that GTMetrix doesn't score your website down even with a 0% score:
https://sirv.com/help/resources/remove-query-strings-from-static-resources/
Instead, prioritise your time to fix the important PageSpeed recommendations that will make your pages load faster.
Place this in your theme's functions.php file or create a plugin file.
function remove_script_style_version( $src ) {
if ( strpos( $src, 'ver=' ) ) {
$src = remove_query_arg( 'ver', $src );
}
if ( strpos( $src, 'x54532' ) ) {
$src = remove_query_arg( 'x54532', $src );
}
return $src;
}
add_filter( 'style_loader_src', 'remove_script_style_version', 1000 );
add_filter( 'script_loader_src', 'remove_script_style_version', 1000 );
// Remove Query String
function nerodev_remove_query_string($src) {
$parts = explode('?ver=', $src);
return $parts[0];
}
add_filter('script_loader_src', 'nerodev_remove_query_string', 15, 1);
add_filter('style_loader_src', 'nerodev_remove_query_string', 15, 1);
Source is here
Related
I have some PowerPoint slideshow files, .ppsx, with mime-type application/vnd.openxmlformats-officedocument.presentationml.slideshow, that I want to upload to WordPress. However, when I try to upload it to the media browser, I get the error "Sorry, this file type is not permitted for security reasons.".
This is despite the fact that .ppsx files are in the list of allowed file types and mimetypes.
When you upload a file, WordPress does some security checks on the file in the wp_check_filetype_and_ext function in wp-include/functions.php:2503. Part of these checks is to validate the given mimetype of the file with the mimetype that PHP detects, using the PHP function finfo_file().
However, finfo_file() isn't always accurate, and its results are often OS dependent. In the specific case of .ppsx files, finfo_file() can read the mimetype as application/vnd.openxmlformats-officedocument.presentationml.presentation. WordPress sees this as a potential security risk because it doesn't match the given mimetype for that file extension and shuts down the upload.
wp_check_filetype_and_ext() also has a filter, and we can use this to our advantage:
function my_check_filetype_and_ext( $info, $file, $filename, $mimes, $real_mime )
{
if ( empty( $check['ext'] ) && empty( $check['type'] ) )
{
$secondaryMimetypes = ['ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation'];
// Run another check, but only for our secondary mime and not on core mime types.
remove_filter( 'wp_check_filetype_and_ext', 'my_check_filetype_and_ext', 99, 5 );
$info = wp_check_filetype_and_ext( $file, $filename, $secondaryMimetypes );
add_filter( 'wp_check_filetype_and_ext', 'my_check_filetype_and_ext', 99, 5 );
}
return $info;
}
add_filter( 'wp_check_filetype_and_ext', 'my_check_filetype_and_ext', 99, 5 );
In vanilla WordPress, there is no way to have multiple mimetypes for a single filetype. The above filter runs the mimetype checks again for a secondary set of filetype/mimetype pairs if it fails the first set of pairs. By allowing .ppsx files with the presentation mimetype, you can now upload .ppsx files!
You need to add some code in your configure.php file to upload any type of
define( 'ALLOW_UNFILTERED_UPLOADS', true );
Add this in your configure.php file and you will be able to upload any file format.
or you can follow this link
Following code work fine for me.
function wcAddCustomFileTypeAndExt( $info, $file, $filename, $mimes, $real_mime )
{
if (strpos($filename, '.ppsx') !== false)
{
$info['ext'] = 'ppsx';
$info['type'] = 'application/vnd.openxmlformats-officedocument.presentationml.slideshow';
}
return $info;
}
add_filter('wp_check_filetype_and_ext','wcAddCustomFileTypeAndExt', 99, 5 );
I am considering to improve security of my Wordpress website, and in doing so have come across WP REST API being enabled by default (since WP 4.4 if I'm not mistaken).
What is a safe way to disable it?
By "safe" here I mean that it does not cause unexpected side-effects, e.g. does not break any other WP core functionality.
One possible approach would be to use .htaccess rewrite rules, but surprisingly I haven't found any 'official' instructions on doing so.
Any help or recommendation is greatly appreciated :)
Update:
3rd-party plugins is not the solution I am looking for. Although I'm aware there are plenty of them that solve the task, they include many extra features that slow down the website. I would hope there is a one-line solution to this problem without the overhead of an extra plugin.
Update 2:
Here is the official opinion of Wordpress: https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#can-i-disable-the-rest-api
According to this, the Wordpress team wants future WP functionality to depend on the new REST API. This means there is no guaranteed safe way to disable the REST API.
Let's just hope there are enough security experts taking care of WP security.
Update 3:
A workaround is presented in WordPress API Handbook - you can Require Authentication for All Requests
This makes sure that anonymous access to your website's REST API is disabled, only authenticated requests will work.
From the author original question I've chosen option 2 that came from wordpress official recommendations(https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#can-i-disable-the-rest-api). So just put in your functions.php to let only logged in users use the rest api (but just cross check original link in case my code block is outdated ;) ):
UPD(01-10-2021):
add_filter( 'rest_authentication_errors', function( $result ) {
// If a previous authentication check was applied,
// pass that result along without modification.
if ( true === $result || is_wp_error( $result ) ) {
return $result;
}
// No authentication has been performed yet.
// Return an error if user is not logged in.
if ( ! is_user_logged_in() ) {
return new WP_Error(
'rest_not_logged_in',
__( 'You are not currently logged in.' ),
array( 'status' => 401 )
);
}
// Our custom authentication check should have no effect
// on logged-in requests
return $result;
});
You can disable it for requests other than localhost:
function restrict_rest_api_to_localhost() {
$whitelist = [ '127.0.0.1', "::1" ];
if( ! in_array($_SERVER['REMOTE_ADDR'], $whitelist ) ){
die( 'REST API is disabled.' );
}
}
add_action( 'rest_api_init', 'restrict_rest_api_to_localhost', 0 );
The accepted answer disables all API calls from unauthenticated users, but nowadays lot of plugins are dependent on this API's functionality.
Disabling all calls will lead to unexpected site behavior which happened in my case also when I used this code.
For example, ContactForm7 makes use of this API for sending contact info to DB (I think) and for ReCaptcha validation.
I think it would be better to disable some (default) endpoints for unauthenticated users like this:
// Disable some endpoints for unauthenticated users
add_filter( 'rest_endpoints', 'disable_default_endpoints' );
function disable_default_endpoints( $endpoints ) {
$endpoints_to_remove = array(
'/oembed/1.0',
'/wp/v2',
'/wp/v2/media',
'/wp/v2/types',
'/wp/v2/statuses',
'/wp/v2/taxonomies',
'/wp/v2/tags',
'/wp/v2/users',
'/wp/v2/comments',
'/wp/v2/settings',
'/wp/v2/themes',
'/wp/v2/blocks',
'/wp/v2/oembed',
'/wp/v2/posts',
'/wp/v2/pages',
'/wp/v2/block-renderer',
'/wp/v2/search',
'/wp/v2/categories'
);
if ( ! is_user_logged_in() ) {
foreach ( $endpoints_to_remove as $rem_endpoint ) {
// $base_endpoint = "/wp/v2/{$rem_endpoint}";
foreach ( $endpoints as $maybe_endpoint => $object ) {
if ( stripos( $maybe_endpoint, $rem_endpoint ) !== false ) {
unset( $endpoints[ $maybe_endpoint ] );
}
}
}
}
return $endpoints;
}
With this, the only endpoints now open are the ones installed by the plugins.
For complete list of endpoints active on your site, see https://YOURSITE.com/wp-json/
Feel free to edit $endpoints_to_remove array as per your requirement.
If you have custom post type, make sure to add those all to the list too.
In my case, I also changed the default endpoint prefix from wp-json to mybrand-api. This should act a deterrent for bots that were making thousands of brute-force requests.
Here is what I did:
// Custom rest api prefix (Make sure to go to Dashboard > Settings > Permalinks and press Save button to flush/rewrite url cache )
add_filter( 'rest_url_prefix', 'rest_api_url_prefix' );
function rest_api_url_prefix() {
return 'mybrand-api';
}
Disabling REST API was not a bad idea, after all.
It actually opened a huge hole in all websites!
In wordpress 4.4 there was a way
Here, I've found a possible solution with .htaccess but should be carefully tested in combination with whatever else is in your .htaccess file (e.g., pretty-url rules added by wordpress itself):
# WP REST API BLOCK JSON REQUESTS
# Block/Forbid Requests to: /wp-json/wp/
# WP REST API REQUEST METHODS: GET, POST, PUT, PATCH, DELETE
RewriteCond %{REQUEST_METHOD} ^(GET|POST|PUT|PATCH|DELETE) [NC]
RewriteCond %{REQUEST_URI} ^.*wp-json/wp/ [NC]
RewriteRule ^(.*)$ - [F]
A very drastic method, is also to have a 404.html webpage in your root and then add this line:
# WP REST API BLOCK JSON REQUESTS
# Redirect to a 404.html (you may want to add a 404 header!)
RewriteRule ^wp-json.*$ 404.html
Note that, unless you use a static page, i.e., not involved with wordpress functions, if you want to return a 404 error with an appropriate error page, this is a complete separate topic, with a lot of issues when Wordpress is involved
if you want to disable Wordpress REST API completely use this code:
// Disable Wordpress REST API
remove_action( 'init', 'rest_api_init' );
remove_action( 'rest_api_init', 'rest_api_default_filters', 10 );
remove_action( 'rest_api_init', 'register_initial_settings', 10 );
remove_action( 'rest_api_init', 'create_initial_rest_routes', 99 );
remove_action( 'parse_request', 'rest_api_loaded' );
With the plugin "Disable REST API" you can select which APIs you want to enable, e.g. the contact form 7 API. See the plugin's settings (yoursite.com/wp-admin/options-general.php?page=disable_rest_api_settings)
add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');
There are several points you need to "turn off". Also, you might want to place some kind of notice to someone coming to that page...
Here is what I used (and was checked):
function itsme_disable_feed() {
wp_die( __( 'No feed available, please visit the Example!' ) );
}
add_action('do_feed', 'itsme_disable_feed', 1);
add_action('do_feed_rdf', 'itsme_disable_feed', 1);
add_action('do_feed_rss', 'itsme_disable_feed', 1);
add_action('do_feed_rss2', 'itsme_disable_feed', 1);
add_action('do_feed_atom', 'itsme_disable_feed', 1);
add_action('do_feed_rss2_comments', 'itsme_disable_feed', 1);
add_action('do_feed_atom_comments', 'itsme_disable_feed', 1);
As per wp_die() docs:
This function complements the die() PHP function. The difference is
that HTML will be displayed to the user. It is recommended to use this
function only when the execution should not continue any further. It
is not recommended to call this function very often, and try to handle
as many errors as possible silently or more gracefully.
Hope this helps.
I am creating translations for my plugin.
To fetch .mo files from my-plugin/languages directory , I use the function
//Load translation
function load_plugin_textdomain() {
load_plugin_textdomain( 'my-plugin', FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );
}
add_action( 'plugins_loaded', 'load_plugin_textdomain' );
How can i set the location to wp-content/languages
Setting the location to ABSPATH.'/wp-content/languages' doesn't work.
I'm aware you've accepted your own answer, but although it will work it's against WordPress standards.
The load_plugin_textdomain will load from the global languages directory without modification and should be used for bootstrapping plugin translations. The path you specify as the third argument is a fallback to be used in case the global language file is not installed.
To clarify how it works: WordPress will look in the global languages directory strictly at <WP_LANG_DIR>/plugins/my-plugin-<locale>.mo. So as long your text domain and locale code are correct, it will be loaded.
If it isn't found, WordPress will look at the path you've specified which must be relative to the wp-content/plugins directory.
Historically (prior to WP 4.6) the third argument was loaded first, but WordPress decided to swap the order, favouring community translations (globally installed) over author-provided translations (shipped with plugin ).
If anybody else is looking for the anwser , Here it is
function load_txtdomain() {
$locale = apply_filters( 'plugin_locale', determine_locale(), 'my-plugin' );
load_textdomain( 'my-plugin', WP_LANG_DIR . '/my-plugin-' . $locale . '.mo' );
}
add_action('plugins_loaded','load_txtdomain');
How do I fix this site speed recommendation with wordpress to remove query strings from static resources.
Resources with a "?" in the URL are not cached by some proxy caching servers. Remove the query string and encode the parameters into the URL for the following resources:
http://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js?ver=4.5.3
/wp-content/cache/nextend/web/n2-ss-2/n2-ss-2.css?1467994835
/wp-content/cache/nextend/web/n2/n2.js?1467994835
/wp-content/plugins/smar ... edia/dist/smartslider-frontend.min.js?1467908685
/wp-content/plugins/smar ... artslider-simple-type-frontend.min.js?1467908685
/wp-content/plugins/smar ... nd/media/dist/nextend-frontend.min.js?1467908685
/wp-content/plugins/smar ... dia/dist/nextend-webfontloader.min.js?1467908685
/wp-content/themes/wootique-child/style.css?ver=4.5.3
/wp-content/themes/wootique/style.css?ver=4.5.3
/wp-includes/js/wp-embed.min.js?ver=4.5.3
/wp-includes/js/wp-emoji-release.min.js?ver=4.5.3
Wordpress seems to add these strings automatically.
this should do the job..
this removes the querystring on the frontend not the admin site.
Update: Add this into your functions.php file. Ensure that its kept within the PHP tags.
function rm_query_string( $src ){
$parts = explode( '?ver', $src );
return $parts[0];
}
if ( !is_admin() ) {
add_filter( 'script_loader_src', 'rm_query_string', 15, 1 );
add_filter( 'style_loader_src', 'rm_query_string', 15, 1 );
}
This plugin will remove query strings from static resources like CSS & JS files, and will improve your speed scores in services like PageSpeed, YSlow, Pingdoom and GTmetrix.
Resources with a “?” or “&” in the URL are not cached by some proxy caching servers, and moving the query string and encode the parameters into the URL will increase your WordPress site performance significant.
// Remove Query String
function nerodev_remove_query_string($src) {
$parts = explode('?ver=', $src);
return $parts[0];
}
add_filter('script_loader_src', 'nerodev_remove_query_string', 15, 1);
add_filter('style_loader_src', 'nerodev_remove_query_string', 15, 1);
I found this here
I'm working on a WordPress site and suddenly all our plugins are malfunctioning. Inspect Elements shows the following:
GET http://example.com/wp-content/plugins/ninja-forms/css/qtip.css?ver=3.8.2 404 (Not Found) (index):295
GET http://example.com/wp-content/plugins/ninja-forms/js/dev/word-and-character-counter.js?ver=3.8.2 404 (Not Found) (index):299
GET http://example.com/wp-content/plugins/ninja-forms/css/ninja-forms-display.css?ver=3.8.2 404 (Not Found) (index):294
GET http://example.com/wp-content/plugins/ninja-forms/css/jquery.rating.css?ver=3.8.2 404 (Not Found) (index):296
GET http://example.com/wp-content/plugins/ninja-forms/js/min/ninja-forms-display.min.js?ver=3.8.2 404 (Not Found)
These files are all set to 755 and do exist on our server. Can anyone help us figure out why ?ver=3.8.2 is appended and how to remove it?
That's added by WordPress as a way of versioning the scripts. It's intended to be used as a cache buster if you update a stylesheet/script file but don't change the name. You can tell WordPress to not do this by filtering it out. Add this to functions.php or a plugin.
add_filter( 'style_loader_src', 'remove_versions_from_scripts_and_stylesheets', 999 );
add_filter( 'script_loader_src', 'remove_versions_from_scripts_and_stylesheets', 999 );
function remove_versions_from_scripts_and_stylesheets( $src ) {
if ( strstr( $src, 'ver=' ) ) {
$src = remove_query_arg( 'ver', $src );
}
return $src;
}
Keep in mind this is just going to remove the version at the end, there may be a bigger issue. If those files do exist on the server, the version thing wouldn't actually prevent them from loading.