-
-
Save BeardedGinger/edcc6f91809073cd3695d1129ad24958 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: Users Network Post Counts | |
* Plugin URI: http://limecuda.com | |
* Description: Gets post counts for users across multisite network and updates meta on weekly cron | |
* Version: 1.0.0 | |
* Author: LimeCuda | |
* Author URI: http://limecuda.com | |
*/ | |
// If this file is called directly, abort. | |
if ( ! defined( 'WPINC' ) ) { | |
die; | |
} | |
// Create cron job on plugin activation | |
register_activation_hook( __FILE__, 'update_users_network_post_counts' ); | |
/** | |
* Schedule the cron job to run function for setting post counts for authors | |
* | |
* @since 1.0.0 | |
* @uses wp_schedule_event() | |
*/ | |
function update_users_network_post_counts() { | |
wp_schedule_event( time(), 'daily', 'update_users_network_post_counts_hook' ); | |
} | |
add_action( 'update_users_network_post_counts_hook', 'as_users_network_post_count_set' ); | |
/** | |
* The users for the network are all subscribers on the main blog | |
* | |
* This function loops through those users, gets their associated blogs, loops | |
* through those blogs and gets the post count for that user from each blog | |
* | |
* The sum of the counts is then saved as user meta with the meta key of | |
* "network_post_count" for each user | |
* | |
* @since 1.0.0 | |
* @uses switch_to_blog() | |
* @uses count_user_posts() | |
* @uses update_user_meta() | |
*/ | |
function as_users_network_post_count_set() { | |
$args = array( | |
'role' => 'Subscriber', | |
'fields' => 'ID' | |
); | |
$users = new WP_User_Query( $args ); | |
// If we have users | |
if( $users->results ) { | |
// Loop through each of the users | |
foreach( $users->results as $user_id ) { | |
// Reset post count variable per user | |
$network_post_count = array(); | |
// Get the users blogs and loop through them | |
$blogs = get_blogs_of_user( $user_id ); | |
foreach( $blogs as $blog ) { | |
switch_to_blog( $blog->userblog_id ); | |
// Update the post count array with post count from each blog | |
$network_post_count[] = count_user_posts( $user_id ); | |
restore_current_blog(); | |
} | |
// Get the total count of posts from each blog | |
$network_post_count = array_sum( $network_post_count ); | |
$count = str_pad( $network_post_count, 2, '0', STR_PAD_LEFT ); | |
update_user_meta( $user_id, 'network_post_count', $count ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment