I have a small problem with a code that works most of the time. I just discovered it cannot be used when I bulk edit custom post type.
If I’m on individual post page and hit publish, the custom post type gets published and the user meta gets updated.
If I use the bulk edit to publish many posts at once, the user meta is not updated.
function sa_ads_count() {
global $wpdb, $post;
$authordata = get_userdata($post->post_author);
$author = $authordata->ID;
// get initial count
$single = true;
$ads_count = get_user_meta( $author, 'ads_count', $single );
if ( strlen( $ads_count ) > 0 ) {
$ads_count = intval( $ads_count ); // make sure it's a number
$ads_count++; // increment by one
} else {
// meta isn't set, so we'll create it
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT post_status, COUNT(ID) as count FROM $wpdb->posts WHERE post_author = %d AND post_type = 'post_type' GROUP BY post_status", $author ) );
$stats = array();
foreach ( $rows as $row )
$stats[ $row->post_status ] = $row->count;
$ads_count = isset($stats['publish']) ? $stats['publish'] : 0;
}
update_user_meta( $author, 'ads_count', $ads_count );
}
add_action( 'pending_to_publish', 'sa_ads_count' );
Any idea what is wrong here? Is it a WordPress limitation or this can be solved?
The thing is, I need this hook as I only want to count and store for every user, the number of posts that I approve and publish.
Later on, I want to change new post status directly to publish based on the number of posts the user has approved. This I already achieved.
Try using the $post parameter: