| 
	自定义查询的方法
	默认的查询 
	
		
			global $wpdb;
			$comments = $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_approved = '1' Limit 0, 10" ); 
	所以: 
	
		
			global $wpdb;
			$user_id  = 57;
			$comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_approved = '1' AND user_id = '%d' Limit 0, 10", $user_id ) ); 
	还可以: 
	
		
			global $wpdb;
			$user_ids = array( 57, 105, 567, 2820 );
			$comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_approved = '1' AND user_id IN(%s) Limit 0, 10", $user_ids ) ); 
	还可以对其进行缓存以提升加载速度: 
	
		
			global $wpdb;
			$user_ids = array( 57, 105, 567, 2820 );
			$key      = md5( serialize( $user_ids ) );
			$comments = get_transient( $key );
			if( false === $comments ) {
			    $comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_approved = '1' AND user_id IN(%s) Limit 0, 10", $user_ids ) );
			    set_transient( $key, $comments, 10800 );  
	使用HOOK过滤的方法
	
		
			add_filter( 'comments_clauses', 'pw_comments_by_users', 10, 2 );
			$comments = get_comments();
			remove_filter( 'comments_clauses', 'pw_comments_by_users' );
			 
			function pw_comments_by_users( $clauses, $wp_comment_query ) {
			    $clauses['where'] .= ' AND user_id IN (57,105,567,2820)';
			    return $clauses;
			} 
	结论
	使用自定义查询并对查询进行缓存的方法性能较好,使用HOOK过滤的方法比较简单,但是注意一定要在查询后移除HOOK,否则会影响到其它地方对于评论的查询。(责任编辑:最模板) |