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.
Related
I am making changes in my theme templates in OpenCart 3. Due to template caching I have to clear cache every time under "storage/cache" directory. It is very annoying when working and previewing changes frequently during development. Please provide some solution how we can configure caching according to production and development environment.
Note: I have already searched for solutions online but there is no solution related to template caching. Solutions are available to disable image caching but "Image Caching" and "Template Caching" are different features provided in Opencart.
You might need to upgrade to a more recent version of OpenCart3 - the first one (3.0.0.0) didn't have a way of doing this in the GUI.
More recent versions, such as 3.0.2.0, have a gear on the admin dashboard. Click the gear and you get options to disable caching.
Another way to do this:
Open to system\library\template\Twig\Cache\Filesystem.php, find following lines of code
public function load($key)
{
if (file_exists($key)) {
#include_once $key;
}
}
Comment out as in the following code:
public function load($key)
{
// if (file_exists($key)) {
// #include_once $key;
// }
}
This will remove the template cache of the twig and recreate every time, once development is over you have to remove the comment.
You can also do this from CODE directly if you have the access. Go to this file path below via ftp or cPanel:
system\library\template\Twig\Environment.php
Find
$this->debug = (bool) $options['debug'];
Replace:
$this->debug = (bool) true;
Opencart Version 3.0.2.0
I was having same problem, try working in theme editor or the actual raw twig file, after an hour or two i tried this it worked.
Delete the changes in theme editor and got back editing actual twig file
my screen shot
I think you edit the template as the path: Design->Theme Editor before.
Clear all of the date in the oc_theme data table of your database.
Scott's answer is best but in case it's not available due to version or you want to disable it programmatically you can do this anywhere before the twig is rendered:
$this->config->set('template_cache', false);
in OC 3.0.3.6, if you have some twig extension, like twig managers, after changes maded you should select that extention in modifications and refresh push button on top right corner.
P.S. loose whole day to find this, hope it helps someone
This is similar to Scott's answer but just on the database/backend. In case you can't rely on the UI and can only access the DB (like me, I'm messing up with the UI) it's on settings table search for 'developer_theme' key and set it to false or 0.
UPDATE `oc_setting` SET `value` = '0' WHERE `oc_setting`.`key` = 'developer_theme';
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
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 :)
I am trying to delete some CCK nodes in Drupal using a standalone PHP script while logged in as anonymous user
if(empty($total_deals_for_this_pl)){
$node_nid = $single_result['nid'];
global $user;
$original_user = $user;
$user = user_load(1);
print $node_nid."<br>";
node_delete($node_nid);
$user = $original_user;
}
I am able to retrieve all the nid's successfully but the nodes are not getting deleted. I am loading Drupal as follows
chdir('C:\wamp\www\mysite\platform'); //my drupal resides here
require_once './includes/bootstrap.inc';
include_once './includes/common.inc';
Node_delete() has an access check for delete permissions inside it.
Test again with anonymous users given permission to delete nodes.
Also try adding
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
If that doesn't work you could try up to the session phase:
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
and finally the full dealio:
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
Three options:
Generally, I would recommend using VBO for this kind of thing. Its a more robust solution than a custom script. It's pretty easy to set up and once you've used it you'll probably think of a dozen other ways to use it.
Failing that, make your own module and stick your custom script inside a proper hook. Your custom script on its own might not be playing along with what other modules are expecting.
If you still want to have your own separate script I suspect it's the bootstrap code that's failing. Check out drupal_bootstrap for the options available to you.
Is it possible with PHP(5) or other Linux tools on an apache debian webserver to get the file requests a single http request made?
for performance reasons i would like to compare them with the cached "version" of my cake app.
non-cached that might be over 100 in some views.
cached only up to 10 (hopefully).
afaik there are 3 main file functions:
file_get_contents(), file() and the manual fopen() etc
but i cannot override them so i cannot place a logRequest() function in them.
is there any other way? attaching callbacks to functions? intercepting the file requests?
This suggestion does not seems intuitive, but you can take look on xdebug - function trace
Once you have xdebug installed and enabled, you can using all sort of configuration to save the profiling into a disk file and you can retrieve it later. Such as profiling results for different URL save into different disk file.
To monitoring file system related functions, you can do a parse of the text file(profiling results) and do a count of matchable functions (programmable or manually)
The way I would do it would be to create a custom function that wraps around the one you need.
function custom_file_get_contents($filename) {
$GLOBALS['file_get_contents_count']++;
return file_get_contents($filename);
}
And just replace all of your calls to file_get_contents with custom_file_get_contents. This is just a rudimentary example, but you get the idea.
Side note, if you want to count how many files your script has included (or required), see get_included_files()
You can use Xdebug to log all function calls
Those so-called "function traces" can be a help for when you are new to an application or when you are trying to figure out what exactly is going on when your application is running. The function traces can optionally also show the values of variables passed to the functions and methods, and also return values. In the default traces those two elements are not available.
http://www.xdebug.org/docs/execution_trace
Interesting question. I'd start with the stream_wrapper ... try to replace them with custom classes.
There is a pecl extention called ADB (Advanced PHP Debugger) that has tow functions that would be very useful for a cse like this - override_function() and rename_function(). You could do something like this:
rename_function('file_get_contents', 'file_get_contents_orig');
function file_get_contents($filename) {
logRequest();
return file_get_contents_orig($filename);
}
It looks like ADB is pretty easy to install, too.
See http://www.php.net/manual/en/book.apd.php