Programmatically block commenting by restricting view of comment form

All we need is an easy explanation of the problem, so here it is.

A forum bridge plugin has the following:

        // Check role is_banned (int 1||0 )
    if ( $this->visitor['is_banned'] === 1 ) {
        // remove capability from the user and any roles
        $user = new WP_User( $user_id );
        $user->set_role( 'subscriber');
        $user->remove_all_caps();
        $user->remove_role( 'subscriber' );

        if ( is_multisite() ) {
            update_user_status( $user_id, 'spam', 1 );
        }
    }

The database shows no wp_capabilities. Unfortunately, the WordPress user can still submit comments.

Is it possible to create a role without commenting abilities?

This question only is for settings

How to block a someone from commenting?

I’m curious if a filter could be added to remove the comment form from anyone with a particular role. In other words, create a role called ‘banned’ and if that role is present then call a function which removes the comment form from view OR create a user meta called banned, set to 1, test for presence of flag to show form.

Does anyone have any other ideas?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I wonder if you mean this kind of approach:

add_filter( 'init', function()
{
    $u = wp_get_current_user();

    if( $u->exists() && in_array( 'banned', $u->roles, true ) )
        add_filter( 'comments_open', '__return_false' );
} );

where we check if the current user has the custom banned role.

If that’s the case then we force all comments to be closed through the comments_open filter.

That means this user should not be able to see the comment form or post a comment directly to wp-comments-post.php, because of the comments_open() checks.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply