Limit comments displayed on basis of user_id

The pre_get_comments hook

Note that the single post’s comments are fetched with get_comments(), within the comment_template() function.

The get_comments() function is just a WP_Comment_Query object wrapper, so we can restrict the comment query with the pre_get_comments hook.

Example #1

Here’s a simple user_id restriction example:

! is_admin() && add_action( 'pre_get_comments', function( \WP_Comment_Query $q )
{
    if( $uid = get_query_var( 'author_id_to_limit' ) )
        $q->query_vars['user_id'] = (int) $uid; 
});

where you might add further constraints, so you don’t modify other comment lists.

Example #2

We could restrict it more with:

// Let's begin where the main loop starts:
add_action( 'loop_start', function( \WP_Query $q )
{
    // Target the main loop
    if( ! in_the_loop() )
        return;

    // Modify the get_comments() call
    add_action( 'pre_get_comments', function( \WP_Comment_Query $q )
    {
        if( 
               $uid = get_query_var( 'author_id_to_limit' )   // Get the user input
            && ! did_action( 'wpse_mods' )                    // Run this only once

        ) {
            // Set the comment user id
            $q->query_vars['user_id'] = (int) $uid; 

            // Activate the temporary action
            do_action( 'wpse_mods' );
        }
    });
});

i.e. we want to target the first get_comments() call after the main loop starts.

You might use other hooks, some themes have specific hooks that might be easier to target.

Modify the comments count accordingly

If we want to modify the displayed comments number, then we could use the get_comments_number filter.

The get_comments_number() function uses the comment_count property of the $post object, that originates from the wp_posts table. So that will not help us here.

We can instead re-use the comments query, to update the comment number, exactly when our temporary wpse_mods action as fired only once (you might have to adjust that to your needs)

! is_admin() && add_action( 'the_comments', function( $comments, \WP_Comment_Query $q )
{
    $request = $q->request;

    add_filter( 'get_comments_number', function( $number ) use ( $request ) 
    {
        // Override the comments number after our previous modifications
        if( 1 === did_action( 'wpse_mods' ) )
        {                   
            global $wpdb;       
            // Modify the comments query to our needs:
            $number = $wpdb->get_var( 
                str_replace( 
                    'SELECT * ', 
                    'SELECT COUNT(*) ', 
                    $request 
                )
            );
        }
        return $number;
    } );        
    return $comments;
}, 10, 2 );

Leave a Comment