Wordpress - Stop plugins from requesting updates - php

I'm looking for a way to actually stop plugins from querying their developers sites to find out if there is a new version.
From running New Relic on a client site I'm working on I can see that outside calls to developer sites (such as WPMUdev) take a hell of a long time to complete, and must be tying up CPU time that would be much better utilised by actual processes that are needed.
Needless to say, there is no reason for a live site to ever be updated directly, so I'm looking for a way to stop these queries happening. Updates can then be done on a local copy and pushed via GIT.
TIA, Thall.

Disable automatic WordPress plugin updates:
add_filter( 'auto_update_plugin', '__return_false' );
Put above code in functions.php
Disable automatic WordPress theme updates:
add_filter( 'auto_update_theme', '__return_false' );
Disable automatic updates in WordPress by adding this line of code in your wp-config.php file:
define( 'WP_AUTO_UPDATE_CORE', false );

Agree with you.
I've came through a post which helps you to stop asking about you for the plugin update. For example I've wp-csv plugin, code in functions file will be like:
function filter_plugin_updates( $value ) {
unset( $value->response['wp-csv/wp-csv.php'] );
return $value;
}
add_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );
Ref link: https://wordpress.stackexchange.com/questions/25358/turn-off-auto-update-for-single-plugin?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Related

Wordpress functions.php won't save using unset() PHP function

I have the unset function in my functions.php theme file and WordPress no longer allows me to save my code in the editor.
I'm using it to unset product tabs on WooCommerce as per this code (found on the WooCoomerce site - https://docs.woocommerce.com/document/editing-product-data-tabs/):
add_filter( 'woocommerce_product_tabs', 'custom_remove_product_tabs', 98 );
function custom_remove_product_tabs( $tabs ) {
unset( $tabs['description'] ); // Remove the description tab
return $tabs;
}
With this code in I get the generic error of: "Something went wrong. Your change may not have been saved. Please try again. There is also a chance that you may need to manually fix and upload the file over FTP." when saving my functions.php file. If I comment out the line with the unset function is saves just fine.
It does work on the site if I save this code using FTP etc so I appreciate some may say just do that, but I like to quickly edit things inside WordPress sometimes which is no longer possible so want to understand why it's happening (and WordPress have docs on using this function themselves so it's driving me mad!). I've tried adding a standard php unset function with a generic variable to check it's not WooCommerce related but this doesn't work either.
Am I missing something? If not, is it a server setting? We're using PHP 7.4 on a litespeed server so should be up to date. I'm not sure if there is a way to see a more detailed error log from this issue so if there is any help finding it would be great.
Thanks for any help!

Disable WPML translations on /wp-admin (serialize and deserialize increases page load time)

We use WPML plugin for WordPress. We would like it to be disabled when we access /wp-admin. Is this possible at all?
Furthermore, we've noticed an increase in page load time when a lot of content is present (due to the serialize and deserialize) so this makes the wp-admin interface unbearably slow.
Does anybody know how we can achieve this?
Try do do this:
add_action('admin_init', 'disable_wpml_for_admin');
function disable_wpml_for_admin() {
if (is_admin()) {
// don't forget to do for the same way for all wpml extensions
deactivate_plugins(
array(
'/wpml-translation-management/plugin.php'
),
true, // silent mode (no deactivation hooks fired)
false // network wide
);
}
}
It based on https://wordpress.stackexchange.com/questions/159085/deactivate-plugin-for-a-specific-user-group
I wanted to put get_current_screen() function to check that we are in admin area, but description told us that it not defined on all admin pages and in some cases you will get error, that's why I check only is_admin() — but it's mean that until you legged as admin even you are on client side — WPML will not work for you.

Make WordPress WP-API faster by not loading theme and plugins

I would like to make requests to the WordPress API much faster. My API is implemented in a plugin (using register_rest_route to register my routes). However, since this is a plugin, everything is loaded with it (the child-theme and the theme) and basically a query to this API is taking half a second because of all this useless parts loaded.
Doesn't WordPress API can be used in another way? Since most plugin making use of the WP-API doesn't need any other plugins to be loaded, even less a theme... I don't understand how they could miss that.
Is there anyway to do this?
Yes, it is possible. In one of my plugins where I need the minimal WordPress core (DB without plugins & themes) here is what I do:
<?php
define('SHORTINIT', true); // load minimal WordPress
require_once PATH_TO_WORDPRESS . '/wp-load.php'; // WordPress loader
// use $wpdb here, no plugins or themes were loaded
The PATH_TO_WORDPRESS constant I made up; you just need to point that to the correct path. In plugins for example, it might look like:
require_once dirname(__FILE__) . '/../../../wp-load.php'; // backwards 'plugin-dir/plugins/wp-content'
Setting SHORTINIT to true certainly does help performance a bit.
With WP_DEBUG disabled, the time it takes to bootstrap WordPress are as follows:
Without SHORTINIT: ~0.045 seconds
With SHORTINIT: ~0.0015 seconds
If this is for your own site where you demand performance, you can probably increase this a bit by enabling an OpCache (e.g. APC or PHP OpCache in recent versions).
But I believe the 2 lines of code above to define SHORTINIT and require wp-load.php are what you're looking for.
To clarify, this file is a part of a plugin, but it is called independently of WordPress itself (via Ajax and directly). It never gets included or used by any other parts of the plugin or WP itself.
EDIT: Since the OP is actually concerned with the WP-API, not WordPress in general, I am adding this to address the actual question. I'll leave the original answer content in case it can help someone else.
I did further testing with the WP API and like #David said in his answer, the issue is probably something else.
I loaded up 12 plugins in addition to the rest api, some fairly "large" plugins, and my local install has about 25 themes installed (one active of course). I edited WordPress' index.php file and used microtime(true) to record when everything started, and then edited one of the REST controllers to calculate how long it took from start to getting to the API endpoint.
The result on my system is consistently around 0.0462 - 0.0513 seconds (no PHP OpCache, and no other system load). So it appears bootstrapping all of WordPress has little impact on performance.
If the requests are taking half a second, the bottleneck is elsewhere and cutting out plugins and themes is going to have minimal impact. At least this is what I found.
I think you might be focusing on the wrong issue.
Loading php files is not nearly as slow as reading from your db and this is likely to be your 500ms load time. You should actually look at reducing this anyway (cache wp-options, etc), but what i suggest to you in relation to the api, is to cache the output using a mu-plugin. Using exit we can load output from file and serve that instantly.
Our Method:
1. Create a folder called mu-plugins in the wp-content folder (may already be there)
create a file called api-cache.php
enter this code into your file:
function get_api_cache(){
//dont run if we are calling to cache the file (see later in the code)
if( isset($_GET['cachecall']) && $_GET['cachecall'] === true)
return;
$url = "$_SERVER[REQUEST_URI]";
//do a little error checking
$uri= explode('/',$url);
//we have a array (1st key is blank)
if( $uri[1] !== 'wp-json' || $uri[2] !== 'wp' || $uri[3] !== 'v2'){
return;
}
//lock down the possible endpoints we dont want idiots playing with this...
$allowed_endpoints= array(
'posts'
);
$endpoint= array_pop($uri); // not sure if this is valid or not, is there more structure to some api calls?
if( !in_array( $endpoint, $allowed_endpoints) ){
return;
}
//ok reasonably confident its a api call...
$cache_folder= get_stylesheet_directory().'/api_cache/';
// prob best if not within php server but to get you going
if(! file_exists ( $cache_folder ) ){
mkdir($cache_folder); //warning 777!!
}
/*
* Need to choose a method of control for your cached json files
* you could clear out the folder on update post/ taxonomies etc
* or cron clear out hourly/weekly whatever freq you want
*/
if( file_exists($cache_folder.$endpoint.'.json') ){
$json= file_get_contents($cache_folder.$endpoint.'.json');
header('Content-Type: application/json');
echo $json;
exit;// we need nothing else from php exit
} else {
//make sure there will be no errors etc..
$ch = curl_init();
$url= "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]?cachecall=true";
$timeout= 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$json = curl_exec($ch);
curl_close($ch);
file_put_contents($cache_folder.$endpoint.'.json', $json);
}
}
get_api_cache();
Now you should notice a significant difference on your load time on the 2nd load (this first time it is caching the output).
A few disclaimers:
you should read the comments in the code
You need curl
You need to be aware the cache folder is 777, I would strongly suggest you move this away from your theme folder and preferably outside your http accessible files.
There were no catch all hooks to capture the data to be cached, hence i used curl to grab the content, this may change in the future and a hook/filter would improve the process time a bit when creating the cache file.
I have not included a method to update cache files. You need to decide on how often you want to update, a site that gets lots of posts per day and a lot of visits, you might do a cron job to just delete the files (e.g. 3 times a day, hourly, every 10 minutes, etc-- what is a reasonable tradeoff in update time?) or add a hook to save post to only update when your posts change, etc..
add your endpoints to the array for them (you can remove the if statement to allow all endpoints, but then you may have a situation where 404s are being cached!)
You should give this a try this. It is a plug-in that allows you to enable/disable certain plug-ins for post-types, pages and other circumstances.
For the theme part, if you wrote it, it would be easy to add something in the function.php to prevent it from attaching any hooks or filters in the case of an API request.
As a sidenote, couldn't you query de DB directly?
Sorry for my poor english if this is helpful for you.
Put the plugin folder in root wordpress install.
/public_html/my-plugin/my-plugin.php
and include wordpress main file.
require dirname( dirname( __FILE__ ) ).'/wp-load.php';
Or in plugin folder directly access
/public_html/wp-content/plugins/my-plugin/my-plugin.php
require_once dirname(__FILE__) . '/../../../wp-load.php';
Before check wp-load.php file included properly and working.
wp-settings.php file load whole core, plugins and themes files. wordpress is load first mu-plugins files (wp-content/mu-plugins/) and provide after action hook muplugins_loaded. Trigger this action to exit whole other files loaded. You can also find which action hook is provide before muplugins_loaded and stop other files and script execution.
if define constant SHORTINIT before include wp-load.php its includes
some files provide DB,plugin or basic functions. When we want more load core files and not just want load plugins and theme files in this way found a solution.
// file my-plugin.php
//call before include file wp-load.php
global $wp_filter;
$wp_filter = array(
// pass wp hook where to want exit extra wp loaded
'muplugins_loaded' => array(
// prority
1 => array(
// callback function register
'wp_extra_loaded_exit' => array(
'function' => 'wp_extra_loaded_exit',
'accepted_args' => 1
)
)
)
);
function wp_extra_loaded_exit(){
exit;
}
require dirname( dirname( __FILE__ ) ).'/wp-load.php';
// plugin code here.
We check muplugins_loaded hook is define wordpress early you can also find which hook is define before muplugins_loaded then stop this point to after load more wordpress files. -
When you want to test your script open file wp-settings.php and find string muplugins_loaded then echo statement to check.
echo "Wordpress loaded in this point before";
do_action( 'muplugins_loaded' );
echo "After this wordpress not loading"; // Output fail bcz we exit

WordPress - overwrite core function even after theme or site update

I have googled this, of course, but I require a solution that stays put even after I upgrade a theme AND/OR upgrade the entire WordPress site to a newer version.
Basically, before a post is shown, I want to show specific HTML. And I want it absolutely foolproof because I will be handing over the site to an old guy. I also don't want any plugins installed because I am quite sure he will be clicking on stuff randomly. -it must be seamless.
It must be an analog of what this would do like this: (post-template.php)
function the_content( $more_link_text = null, $strip_teaser = false) {
$content = get_the_content( $more_link_text, $strip_teaser );
/**
* Filter the post content.
*
* #since 0.71
*
* #param string $content Content of the current post.
*/
$content = apply_filters( 'the_content', $content );
$content = str_replace( ']]>', ']]>', $content );
$EXTRA_HTML='';
if(is_single()){$EXTRA_HTML='INSERT HTML HERE';}
echo $EXTRA_HTML.$content;
}
I cant get my head around it. What should I put and WHERE? The updates just make it all go away.
To make sure any solution you make up will not be overwritten on post and themes update, the best way around is creating a Child Theme and adding the piece of HTML you want on its proper place. Probably on a loop template or single.php depending on how the base theme is structured.
This way, even if Wordpress or the Core Theme he's using is updated, you'll have your solution online as your Child Theme will not be replaced.
Another solution for this would be using a theme and make sure it's always online by making two simple adjustments on your WP setup:
On wp-content folder create a new folder called mu-plugins and drop your custom made plugin in there. mu-plugins stands for Must Use Plugins and plugins on this folder will always be enabled and can't be turn off unless you delete it from the server folder.
Make sure the user can't edit theme and plugin files by dropping define( 'DISALLOW_FILE_MODS', true ); line on wp-config.php.
Both solutions will help you achieve this customization without a regular user being able to break it by simple button clicking around. If this can still be an issue, you can also hide any admin settings that can cause trouble in the future. I use Adminimize quite often with the solutions above to make sure any user will not click and break stuff around.

What is a better way to implement wp_get_archives modification without touching the wordpress core?

I started my first ever theme or any kind of development in Wordpress since yesterday for my blog, and after getting most of the basic stuff done, I was looking to create an Archive page. The default output for the archive page achieved through the wp_get_archives function is the_title(of the post).
However, I wanted to display the archive posts along with their respective post_date. It seems that the format is hard-coded within the general_template.php (really!! but I am new to WordPress design philosophy to further remark on that)
I did that by directly modifying the general_template.php file in wp-includes directory. I changed the wp_get_archives & get_archives_link functions (main code changes are...)
*wp_get_archives()
............
$text = strip_tags( apply_filters( 'the_title', $result->post_title, $result->ID ) );
$text .= "|||" . date('F j, Y', strtotime($result->post_date));
*get_archives_link()
............
elseif ('withdate_ms' == $format) {
$text_pieces = explode("|||", $text);
$link_html = "\t<li>$before<a href='$url'>{$text_pieces[0]}</a> • {$text_pieces[1]} $after</li>\n";
}
This achieved what I wanted to do. But, I am NOT feeling it is good practice by trying to directly change the core wordpress files (especially for something this trivial). I am new to WP, but I guess there must be a Wordpress-way of achieving this, for sure. How would I go about implementing this modification without touching the core? And will this approach work for other changes to core functionality (for any other set, if I need to change in future)?
Copy-paste the wp_get_archives( ) function into your theme's functions.php file, then rename it (to avoid function name conflicts), and use that function as a drop-in replacement anywhere that you would normally use wp_get_archives( ).
Make sure to copy the entire function and all other functions that are used inside of that function should work just fine.
One thing to note, is that if there are any future updates to wp_get_archives( ), you'll have to either integrate those changes into your new function, or live without those changes, as the updates will have no effect on your function.

Categories