Add New Post Count Meta Key to Wordpress Profile

Description/Instructions

This meta key will count how many posts of a post type a user has published and will add it to their wordpress usermeta under the meta key “user_member_post_count”.

If this snippet helped, feel free to buy me a taco :)

Instructions

Change the TRACED POST TYPE "member" to whatever post type you want.

The meta key would be user_member_post_count and change "member" to whatever post slug you entered below so for example user_profile_post_count or user_event_post_count

 

// Define the post type slug to be tracked
define('TRACKED_POST_TYPE', 'member'); // Change 'member' to your desired post type slug

// Initialize user post count on user registration
function initialize_user_post_count($user_id) {
if (!get_user_meta($user_id, 'user_' . TRACKED_POST_TYPE . '_post_count', true)) {
update_user_meta($user_id, 'user_' . TRACKED_POST_TYPE . '_post_count', 0);
}
}
add_action('user_register', 'initialize_user_post_count');

// Hook into the post submission process to update the count
function increment_user_post_count($post_id) {
$post = get_post($post_id);
if ($post->post_type == TRACKED_POST_TYPE && $post->post_status == 'publish') {
$user_id = $post->post_author;
$count = get_user_meta($user_id, 'user_' . TRACKED_POST_TYPE . '_post_count', true);
$count = $count ? $count : 0;
update_user_meta($user_id, 'user_' . TRACKED_POST_TYPE . '_post_count', ++$count);
}
}
add_action('publish_' . TRACKED_POST_TYPE, 'increment_user_post_count');

// Decrement the post count if a post is deleted or unpublished
function decrement_user_post_count($post_id) {
$post = get_post($post_id);
if ($post->post_type == TRACKED_POST_TYPE && $post->post_status == 'publish') {
$user_id = $post->post_author;
$count = get_user_meta($user_id, 'user_' . TRACKED_POST_TYPE . '_post_count', true);
$count = $count ? $count : 0;
update_user_meta($user_id, 'user_' . TRACKED_POST_TYPE . '_post_count', max(0, --$count));
}
}
add_action('before_delete_post', 'decrement_user_post_count');
add_action('wp_trash_post', 'decrement_user_post_count');
add_action('unpublish_' . TRACKED_POST_TYPE, 'decrement_user_post_count');

// Make it retroactive to count existing posts
function retroactively_count_posts() {
$users = get_users();
foreach ($users as $user) {
$user_id = $user->ID;
$args = array(
'author' => $user_id,
'post_type' => TRACKED_POST_TYPE,
'post_status' => 'publish',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
$count = $query->found_posts;
update_user_meta($user_id, 'user_' . TRACKED_POST_TYPE . '_post_count', $count);
}
}
add_action('init', 'retroactively_count_posts');

 

  • PHP
Copy Code

Let's Chat About this Snippet