0

Is it possible to allow anonymous comments in a CPT? I mean, this config:

  • Allow registered users to comment globally.
  • Allow anonymous users to comment in a CPT.

Thanks!

1 Answer 1

1

There may be a better way around this but I would allow comments on the entire site and make sure that your custom post type supports comments:

<?php 
register_post_type( 'custom', array(
    // ..
    supports => array(
        'comments',
    ),
) );
?>

Then add the following function to your functions.php file:

function hide_comment_form( $post_type = 'custom' )
{
    // If user is logged in return false
    if ( is_user_logged_in() ) {
        return false;
    } else {

        // Else check for special post type
        // If on custom post type single return false           
        if ( is_singular( $post_type ) ) {
            return false;
        }

        // Else return true (hide the form)
        return true;
    }
}

You can then wrap your comment_form() code within the template in the following:

if ( ! hide_comment_form() ) {
    comment_form();
}

The function will always hide the comment form when a user isn't logged in, except when the comment form appears on a custom post type page.

If you didn't want to edit your template file you could also add the following to your functions.php file:

function comment_form_before_function()
{
    if ( hide_comment_form() ) {
        echo '<div style="display: none;">';
    }
}
add_action( 'comment_form_before', 'comment_form_before_function', 1 );

function comment_form_after_function()
{
    if ( hide_comment_form() ) {
        echo '</div>';
    }
}
add_action( 'comment_form_after', 'comment_form_after_function', 99 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.