我使用以下代码来获取用户对其他用户帖子发表的总评论(不包括用户自己帖子上发布的评论):
function grab_custom_user_comments_count( $uid ){
global $wpdb;
$sql = "SELECT COUNT(*) as total
FROM {$wpdb->comments} as c
JOIN {$wpdb->posts} as p ON p.ID = c.comment_post_ID
WHERE c.comment_approved = '1'
AND p.post_status ='publish'
AND p.post_type ='post'
AND p.post_author != c.user_id
AND c.user_id = %d";
$comment_count_others = $wpdb->get_var( $wpdb->prepare( $sql, $uid ) );
return $comment_count_others;
}
$user_comment_count = grab_custom_user_comments_count( $userID );
现在,我想要使用此值更新所有用户metadata,而不是运行此代码。因此,$meta_value
将是评论的总数(如上所示),而$meta_key
可能是custom_user_comments
。
如何为所有用户添加此元数据?如何在用户对其他用户的帖子发表评论时更新该值?
答案 0 :(得分:2)
使用插件:
您必须使用每个功能中提供的用户ID填补空白:
<?php
/**
* Plugin Name: (SO) Comment to User Meta
* Plugin URI: http://stackoverflow.com/a/25464099/1287812
* Author: brasofilo
*/
/**
* Modify all user meta on plugin activation
*/
register_activation_hook( __FILE__, function()
{
# Security checks
if ( ! current_user_can( 'activate_plugins' ) )
return;
$plugin = isset( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';
check_admin_referer( "activate-plugin_{$plugin}" );
# ITERATE THROUGH USERS AND UPDATE METADATA
foreach( get_users() as $user )
{
# http://codex.wordpress.org/Function_Reference/update_user_meta
#
$user_comment_count = grab_custom_user_comments_count( $user->data->ID );
}
});
/**
* Update user meta on comment post
* looks like this hook only runs for logged users, checking for that just to be safe
*
* @param $id Comment ID
* @param $comment_obj Full comment details
*/
add_action( 'wp_insert_comment', function( $id, $comment_obj )
{
# Only on backend and for logged users
if( is_admin() || !is_user_logged_in() )
return;
# CURRENT LOGGED USER
global $user_ID;
get_currentuserinfo();
# POST AUTHOR
# http://codex.wordpress.org/Function_Reference/update_user_meta
#
$user_comment_count = grab_custom_user_comments_count( $comment_obj->user_id );
// You can compare $user_ID and $comment_obj->user_id here
}, 10, 2 );
$comment_obj
传递的wp_insert_comment
包含如下所示的数组,您可以使用get_post( $comment_obj->comment_post_ID )
获取有关当前帖子的信息。
stdClass Object
(
[comment_ID] => 36
[comment_post_ID] => 885
[comment_author] => nicename
[comment_author_email] => email@mail.com
[comment_author_url] =>
[comment_author_IP] => 127.0.0.1
[comment_date] => 2014-08-23 19:16:49
[comment_date_gmt] => 2014-08-23 17:16:49
[comment_content] => Lorem ipsum lorem
[comment_karma] => 0
[comment_approved] => 1
[comment_agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36 FirePHP/4Chrome
[comment_type] =>
[comment_parent] => 0
[user_id] => 1
)