I am creating my first wordpress plug, and am using the WPBP template which is a great timesaver.
In the main of the plugin (called myplugin.php), I added a simple command to write a line of text to a file. That works, however, when I refresh the page (one page of my website), I see approx 4 lines written to my file.
Does the myplugin.php get included / execute many times for each page? If so, why?
Next, what is the best way to enforce only running once per page. I plan to create a PHP object and don't want to create it 4 time. Obviously I could build my own detection if the class exists, but that seems wrong. Surely WP has devised some mechanism to ensure plugin global/main code only runs once.
I am creating my first wordpress plug, and am using the WPBP template which is a great timesaver.
In the main of the plugin (called myplugin.php), I added a simple command to write a line of text to a file. That works, however, when I refresh the page (one page of my website), I see approx 4 lines written to my file.
Does the myplugin.php get included / execute many times for each page? If so, why?
Next, what is the best way to enforce only running once per page. I plan to create a PHP object and don't want to create it 4 time. Obviously I could build my own detection if the class exists, but that seems wrong. Surely WP has devised some mechanism to ensure plugin global/main code only runs once.
Share Improve this question asked Sep 30, 2019 at 0:33 TSGTSG 1054 bronze badges2 Answers
Reset to default 0Plugins are only loaded once per request. Plugins are loaded with this code:
// Load active plugins.
foreach ( wp_get_active_and_valid_plugins() as $plugin ) {
wp_register_plugin_realpath( $plugin );
include_once( $plugin );
/**
* Fires once a single activated plugin has loaded.
*
* @since 5.1.0
*
* @param string $plugin Full path to the plugin's main file.
*/
do_action( 'plugin_loaded', $plugin );
}
This is inside wp-settings.php
, which only loads once, but also note that include_once
is used, meaning that the plugin couldn't be loaded twice even if that code ran twice for some reason.
However, not that I said per request. This means that any AJAX requests that are sent from the page will cause the plugin to be loaded for each of those AJAX requests, in the background. This could explain why the function is running multiple times
In this case you can attach your code functionality to a hook, one of the most common for this case is plugins_loaded
. You can see more details about this hook on the codex.
Like:
<?php
add_action( 'plugins_loaded', function() {
$my_plugin = new Plugin();
$my_plugin()->init();
});
Another approach is use the Singleton pattern for your object class so you can update to an approach like:
<?php
$my_plugin = Plugin::getInstance();
add_action( 'plugins_loaded', [ $my_plugin, 'init' ]);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745119813a4612344.html
评论列表(0条)