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

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

Related

Wordpress minimum load with only REST API functions

I need to run regular updates from external app to wordpress website through REST API. But the performance of the API is awful.
I see around the SHORTINIT method, that loads minimal WP but it doesn't load rest api either.
My question is how can I make a php file that only loads features I need and also respond to all rest api endopoints?
For example if i make a /wm-minimal/index.php how can I make calls to /wp-minimal/wp-json/wp/v2 which is the url part that wordpress api responds?
I've never tried this but it's possible that if you minimal includes the red files you could run do_action('rest_api_init')
This is a big speculative maybe.
Add a filter in the url, add the required files from wp-settings and add do_action('rest_api_init')
Untried.
if ( ! filter_input( INPUT_GET, 'shortinit' ) ) {
define( 'SHORTINIT', true );
}
require_once __DIR__ . '/wp-load.php';
...
do_action('rest_api_init')

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.

How to wp_dequeue_script or wp_deregister_script jquery (not effected) file from wp theme

NOTE: I already use wp_dequeue_script or wp_deregister_script but not successfull
Here is the scenario, i make a image slider plugin that use jquery-cycle2 and it work successfully.
There is a user who used a wp theme and in theme there is a jquery-cycle1, now when he install my plugin the jquery-cycle1 and jquery-cycle2 conflicts, when user delete the jquery-cycle1 file all things work fine and perfectly but i don't want to delete file by user.
Now i am trying that when user install my plugin the jquery-cycle1 in theme close or deregister or stop its effect.
I get file from theme successfully
if((file_exists($theme_file_path."/jquery.cycle.all.js"))){
echo "yes";
}
but i have no idea to close jquery-cycle1 file or stop its effect.
Last Option: I have last solution that delete the file from theme but its my last option.
Please any suggestions, help me.
You will have to place an incompatibility notice on your theme.
It is not possible to attempt to detect the existence of script from server side. You are able to detect queued scripts via the word press methods, however, this assumes that the user has not simply linked the file with a <script></script> tag. The file_exists method assume the file is stored on the server itself - it could be linked from a CDN or another server.
Also, whatever methods you use to detect and remove jQuery-Cycle; You are going to break any feature on the site that uses the existing plugin.
Thus, any solution you able to devise would either be extremely complicated, or would not be generalised enough to account for all these possibilities.
You may be able to use the following to prevent loading your script
if (jQuery().cycle) {
// Script already loaded
console.log("Error: Another version of jQuery-Cycle is already loaded!");
} else {
// Load your script
}
but this cannot unload what is already loaded.
There is a simple hack you can do on you end. In the Cycle2 source replace all $.fn.cycle with $.fn.cycle2 and ).cycle( to ).cycle2(.
I am using the source from here http://malsup.github.io/jquery.cycle2.js
After that You can access it like
$("#id").cycle2({option})
Here is a demo http://jsfiddle.net/33g6z79h/
Here i assume that you are not using cycle events http://jquery.malsup.com/cycle2/api/#events
and cycle extra transitions.
If you are using it you can make a fiddle for your cycle2 implementation and i would be glad to help :)

Lighten my cms loading

I am creating a cms system and so far so good. But as i go further with my project i develloped alot of plugins for my cms like a guestbook, calendar, comments, events, blog,...
Now every plugin is loaded in my index.php file with the require function.
A plugin gets loaded like this.
// START PLUGINS //
/////////////
// COUNTER
ob_start();
require 'plugins/counter/counter.php';
$counter = ob_get_clean();
and the plugins gets displayed only on the pages with the correct TAG like this
$template = file_get_contents('./templates/' . $default_template . '/template.php');
$search = array('[[SITE_TITLE]]', '[[PAGE_TITLE]]', '[[PAGE_CONTENT]]', '[[MENU_LINKS]]', '[[DEFAULT_TEMPLATE]]', '[[COUNTER]]');
$replace = array($site_title, $page_title, $page_content, $newresult, $default_template, $counter);
echo $template
Now, this is the main structure, but in the last few months i have like 35 plugins now. The require plugins gets heavy and i am affraid that my website will go slow with lots of traffic.
Is there an other way i can "require" all the plugins but with less effect on my website speed?
thx for any suggestions. I have been looking arround here but found no solution yet.
There is no silver bullet for optimization. I suggest you turn on Xdebug profiler and find the bottleneck. Then eliminate it.
Also you can follow some common optimization techniques.
A good resource on Stackoverflow.com. Tactics for using PHP in a high-load site
A page from Google.
You can use magic autoload function to require classes only when necessary. Check out: http://www.php.net/manual/en/language.oop5.autoload.php

wp-super-cache, reload from php

Is it possible to reload (or delete) the wp-super-cache from a php script? Is there a specific function for that?
http://ocaoimh.ie/wp-super-cache-developers/ says:Clearing the Cache
The development version of the plugin includes the following function. However, as this code hasn’t been released you cannot depend on this function being available on WordPress blogs just yet.
1 function wp_cache_clear_cache() {
2 global $cache_path;
3 prune_super_cache( $cache_path . 'supercache/', true );
4 prune_super_cache( $cache_path, true );
5 }
If you need this functionality in a plugin now, call prune_super_cache() directly. Please sanity check it however as it’s a very powerful command!Delete the cache files for a single post by using the wp_cache_post_change( $post_id ) function. It will attempt to delete every half-on cache file for that post, as well as any supercache files.
You can reload it from the administration panel. If you want to do it remotely, you can write a script that simply
rm -rf [cache dir]
Just see where you have that dir.

Categories