WordPress multi-site website dynamic statistics tutorial
In a WordPress multi-site environment, managing and monitoring the status of each subsite is a common requirement. One of the basic and practical functions is to display the total number of active subsites in the current multi-site network on the main site. This counter not only visually demonstrates the scale of the network, but also updates in real time when subsites are created or closed, providing accurate data. This article will introduce in detail how to use WordPress core functionality to implement this dynamic counter.
Core function: Obtain the number of websites in a multi-site network
WordPress provides a powerful function get_sites() to query site information in a multi-site network. This function is very flexible and can be filtered and sorted according to a variety of parameters. For our current requirements - just getting the total number of sites - the get_sites() function provides a special parameter count.
When the count parameter is set to true, the get_sites() function will no longer return a WP_Site object array, but will directly return an integer, representing the total number of sites that meet the query conditions. This greatly simplifies the logic of getting the number of sites and avoids unnecessary loop traversals.
Example:
$args = array( 'count' => true // Set to true to directly return the number of sites); $number_of_sites = get_sites( $args ); // $number_of_sites now contains the total number of sites in a multi-site network
Realize real-time update mechanism
To ensure that the counter of the homepage of the main site can be updated in real time as the subsite is created or deleted, we need to hook it to a certain event in WordPress. WordPress's Action Hooks are the key to achieving this goal.
Use wp_head action hook
wp_head is an action hook that fires when each page is loaded, which is located inside the
tag of the HTML document. This means that each time a user visits the homepage of the main site, the code associated with wp_head is executed once, recalculating and displaying the latest number of sites.Although the wp_head hook is usually used to output content inside the
tag, we can also use it to perform computational logic. In the simplified example of this tutorial, we will output the count directly in wp_head.Advanced Options: AJAX
For scenarios where higher performance or no page refresh updates are required, AJAX (Asynchronous JavaScript and XML) can be considered. With AJAX, you can send a request to the server to get the latest number of sites without reloading the entire page and update the counters on the page dynamically. This usually involves WordPress's AJAX API, requiring writing front-end JavaScript and back-end PHP processing functions. Although AJAX provides a smoother user experience, its implementation complexity is also relatively high. For beginners and basic needs, the wp_head method is effective enough.
Practical: Add dynamic counters to the topic
Now, we will implement this dynamic counter in your WordPress theme in combination with the get_sites() function and the wp_head action hook.
step:
- Open the theme's functions.php file: Navigate to your WordPress installation directory and find the wp-content/themes/your active theme name/functions.php file.
- Add the following code: Add the following code block to the end of the functions.php file.
/** * WordPress Multisite Website Number Count Counter* Execute in the wp_head hook to get and output the total number of websites in the current multisite network. */ add_action('wp_head', 'your_multisite_counter_display', 99); function your_multisite_counter_display() { // Define the query parameters, specify that only the count $args = array( 'count' => true ); // Call the get_sites function to get the total number of websites $number_of_sites = get_sites( $args ); // Output the number of websites. In practical applications, you may need to wrap it in an HTML element, // and place it in the specified location of the page through JavaScript. // For demonstration purposes, the count is output as HTML comments and will not be displayed directly on the page. echo '<!-- The total number of websites in the current multi-site network: ' . $number_of_sites . ' -->'; // If you want to be visible directly on the page, you can uncomment the following lines and adjust them according to your theme layout. // But please note that the wp_head hook output is usually located at the top of the or of the HTML document. // echo '<p>Current website number: <strong>' . $number_of_sites . '</strong></p>'; }
Code parsing:
- add_action('wp_head', 'your_multisite_counter_display', 99);
- add_action is a function used by WordPress to register action hooks.
- 'wp_head' specifies that we want the code to be executed within the tag.
- 'your_multisite_counter_display' is the name of the function we are going to define.
- 99 is the priority parameter. The default priority is 10. A higher number means that the function will be executed later. Setting to 99 here is to ensure it is executed after most other wp_head-related scripts, but usually the default value is OK.
- function your_multisite_counter_display() { ... }
- This is a function that actually executes the counting logic.
- $args = array('count' => true); defines the parameter of get_sites and explicitly requires the return of the count.
- $number_of_sites = get_sites( $args ); Execute a query and get the total number of websites.
- echo '';
- Here the number of websites is output as HTML comments. This method will not be displayed directly on the page, but can be viewed in the page source code.
- If you want to be visible directly on the page, it is generally recommended to insert content by calling functions directly in the theme template file to better control the display position.
Extensions and considerations
- More flexible display location: If you want to display counters in specific locations of the page (such as footer, sidebar, or article content), echoing directly in wp_head may not be appropriate. A better approach is to create a shortcode, or encapsulate the counting logic in a function and then call the function in the theme template file.
- Short code example:
function get_multisite_site_count_shortcode() { // Make sure if ( ! is_multisite() ) { return ''; } $args = array( 'count' => true ); $number_of_sites = get_sites( $args ); return 'Current number of websites: <strong>' . $number_of_sites . '</strong>'; } add_shortcode('multisite_count', 'get_multisite_site_count_shortcode'); // Then use [multisite_count] in the content of the article or page editor to display the count. // Or use echo do_shortcode('[multisite_count]');
- Short code example:
- Filtering a specific type of site: The get_sites() function accepts more parameters, allowing you to filter sites with a specific state. For example, you might just want to count public, unarchived sites:
$args = array( 'count' => true, 'public' => 1, // Only public sites are counted 'archived' => 0 // No archived sites); $number_of_sites = get_sites( $args );
For more parameters, please refer to the constructor parameters of WP_Site_Query in the official WordPress document: //m.sbmmt.com/link/79643b609b5bd4b9bdaa3a527707ec39
- Performance considerations: Although get_sites(['count' => true]) is a relatively efficient operation because it avoids loading full site objects. But on extremely high traffic sites, executing database queries every page load can still bring a slight performance overhead. If the real-time requirement is not very strict, consider cache the count results for a period of time (for example, using the set_transient() function), and update it every few minutes or hours.
- Code location: It is recommended to put such functional code into custom plugins instead of theme functions.php. This way, even if the theme is changed, the function will remain unchanged.
Summarize
By leveraging the get_sites() function and wp_head action hook in WordPress multi-site environment, we can easily implement a dynamic, real-time website count counter on the main site. This not only provides intuitive network-scale display, but also provides multi-site
The above is the detailed content of WordPress multi-site website dynamic statistics tutorial. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Stock Market GPT
AI powered investment research for smarter decisions

Clothoff.io
AI clothes remover

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

This tutorial provides detailed instructions on how to add a "Submit Quotation" button to each article in WordPress in a custom article type list. After clicking, a custom HTML form with the article ID pops up, and the form data is AJAX submission and success message display. The content covers front-end jQuery UI pop-up settings, dynamic data transfer, AJAX request processing, as well as back-end WordPress AJAX hook and data processing PHP implementation, ensuring complete functions, secure and good user experience.

PHParrayshandledatacollectionsefficientlyusingindexedorassociativestructures;theyarecreatedwitharray()or[],accessedviakeys,modifiedbyassignment,iteratedwithforeach,andmanipulatedusingfunctionslikecount(),in_array(),array_key_exists(),array_push(),arr

TheObserverdesignpatternenablesautomaticnotificationofdependentobjectswhenasubject'sstatechanges.1)Itdefinesaone-to-manydependencybetweenobjects;2)Thesubjectmaintainsalistofobserversandnotifiesthemviaacommoninterface;3)Observersimplementanupdatemetho

$_COOKIEisaPHPsuperglobalforaccessingcookiessentbythebrowser;cookiesaresetusingsetcookie()beforeoutput,readvia$_COOKIE['name'],updatedbyresendingwithnewvalues,anddeletedbysettinganexpiredtimestamp,withsecuritybestpracticesincludinghttponly,secureflag

Useinterfacestodefinecontractsforunrelatedclasses,ensuringtheyimplementspecificmethods;2.Useabstractclassestosharecommonlogicamongrelatedclasseswhileenforcinginheritance;3.Usetraitstoreuseutilitycodeacrossunrelatedclasseswithoutinheritance,promotingD

This tutorial details how to add a Submit Quotation button to the list item of each custom post type (such as "Real Estate") in WordPress, and a custom HTML form with a specific post ID pops up after clicking it. The article will cover how to create modal popups using jQuery UI Dialog, dynamically pass the article ID through data attributes, and use WordPress AJAX mechanism to implement asynchronous submission of forms, while processing file uploads and displaying submission results, thus providing a seamless user experience.

B-TreeindexesarebestformostPHPapplications,astheysupportequalityandrangequeries,sorting,andareidealforcolumnsusedinWHERE,JOIN,orORDERBYclauses;2.Full-Textindexesshouldbeusedfornaturallanguageorbooleansearchesontextfieldslikearticlesorproductdescripti

This tutorial will provide detailed instructions on how to implement a pop-up submission form in WordPress for a standalone button for each custom post (such as the "Real Estate" type). We will use jQuery UI Dialog to create modal boxes and dynamically pass the article ID through JavaScript. Additionally, the tutorial will cover how to submit form data via AJAX and handle backend logic without refreshing the page, including file uploads and result feedback.
