WordPress plugin executing code twice

Quite simply, it’s loading more than once because you’re probably actually making more than one HTTP request to “WordPress”.

You should not do anything like counting on a plugin load like this, because WordPress can load in many different situations, sometimes more than once for even a single page view.

The wp-cron process, for example, can run in the background on another request in order to handle things like scheduled posts, update checks, trash cleanup, and other such mundane tasks. Those HTTP requests do indeed load plugins, so that plugins can do things when the wp-cron process is called.

Elements of the main Dashboard, such as the “WordPress News”, are shown using Javascript. These are separate requests in the backend to the admin-ajax routines, which load WordPress in order to access the HTTP functions, and then to retrieve data from the WordPress.org RSS feeds. These load most of WordPress, plugins included.

So what you’re counting is not so much a “visit” counter as it is a “hit” counter, and one visit can be more than one hit. If you actually want to count visits, you should count much more selectively, ignoring things like background requests.

  • When a cron process is running, DOING_CRON will be defined.
  • When an AJAX request is running, DOING_AJAX will be defined if it’s going through the admin-ajax system. However, note that many plugins and themes use their own system of callbacks to WordPress, and may not be easily recognizable like this.

So, you can ignore those hits in your counter. But realistically, you’re still going to get “false” count increases from other plugins and themes. So you should instead change your counting method to not count on plugin load, but instead to count on specific WordPress action hooks that you’re wanting to monitor.

Leave a Comment