Hide Comments with Leaky Paywall

Comments on a restricted post can give away what the article says. You can hide the comment section from readers who can't read a post, while keeping comments on free posts and for subscribers who have access.

This needs Leaky Paywall 5.3.0 or later.

Posts only paid levels can read

Add this code to your theme's functions.php file, or to a code snippets plugin such as Code Snippets:

function hw_lp_reader_is_blocked( $post_id ) {
    if ( ! function_exists( 'leaky_paywall_post_is_hard_restricted' ) || ! leaky_paywall_post_is_hard_restricted( $post_id ) ) {
        return false;
    }
    $restrictions = new Leaky_Paywall_Restrictions( $post_id );
    if ( $restrictions->user_role_can_bypass_paywall() ) {
        return false;
    }
    return ! $restrictions->current_user_can_access();
}

add_filter( 'comments_open', function ( $open, $post_id ) {
    return hw_lp_reader_is_blocked( $post_id ) ? false : $open;
}, 20, 2 );

add_filter( 'comments_array', function ( $comments, $post_id ) {
    return hw_lp_reader_is_blocked( $post_id ) ? array() : $comments;
}, 20, 2 );

With this in place:

  • Readers without access to a paid-only post don't see its comments or the comment form.
  • Subscribers whose level gives them access see comments as usual.
  • Roles set to bypass restrictions under Leaky Paywall > Settings > Restrictions, such as administrators, see comments as usual.
  • Free posts and metered posts keep their comments for everyone.

A post counts as paid-only when its Visibility setting limits it to paid levels, or when it falls under a restriction rule that allows no free views.

Metered posts

On a metered post, the number of articles a reader has viewed is counted in their browser, so the server can't tell whether a visit is over the limit. To hide comments when the paywall appears on a metered post:

  1. Go to Leaky Paywall > Settings > Restrictions and set Restriction Method to Automatic or JavaScript.
  2. Add this code the same way as the code above:
add_action( 'wp_footer', function () {
    ?>
    <script>
    document.addEventListener( 'leaky_paywall_shown', function () {
        var comments = document.getElementById( 'comments' );
        if ( comments ) {
            comments.style.display = 'none';
        }
    } );
    </script>
    <?php
} );

Replace comments with your theme's ID for the comment section if it uses a different one.

Still need help? Contact Us Contact Us