-1

I have this code inside my comments.php :

<?php
 // If CPT and not logged in, display a message:
 if ( 'CPT' == get_post_type() && ! is_user_logged_in() ) {
 echo '<p class="must-log-in" style="padding-left:20px; font-size:20px;">You must be logged in to post a comment.' . '</p>';

 echo do_shortcode("[upme_login]");

 }
 ?>

and this code :

   <?php
 // Don't output the comment form if CPT and user isn't logged in

  if ( 'CPT' != get_post_type() || ! array_key_exists( 'comments', $wp_query->query_vars ) ) {

 comment_form();
 }

 ?>

When the user is not logged in it should display a message like You must be logged in.... which is doing, but I see the comment form also which normally I shouldn't see it.

If I remove this || ! array_key_exists( 'comments', $wp_query->query_vars ) everything is working as expected.

How can I do to make it visible if the user is logged in?

What is wrong?

8
  • Does var_dump( $wp_query->query_vars ); around there shows expected results? Might be that global is not accessible there.
    – Rarst
    Nov 24, 2013 at 20:15
  • That is showing expected results, but as I said it's displaying the comment form if the user is not logged in which normally shouldn't display it and if I get rid of || ! array_key_exists( 'comments', $wp_query->query_vars ) is working but I don't want this
    – agis
    Nov 24, 2013 at 20:30
  • But there is no check for user logged in around comment_form() call in your example?..
    – Rarst
    Nov 24, 2013 at 20:32
  • No, it isn't any check for logged in user... but is in the first code
    – agis
    Nov 24, 2013 at 20:41
  • How would second code know what is going on in first code?
    – Rarst
    Nov 24, 2013 at 20:48

1 Answer 1

1

In the first version of your code, you don't check if user is logged in.

In the second attempt your logic is wrong, I guess.

So your code should look like so:

<?php
    // If CPT and not logged in, display a message:
    if ( 'CPT' == get_post_type() && !is_user_logged_in() ) {
        echo '<p class="must-log-in" style="padding-left:20px; font-size:20px;">You must be logged in to post a comment.' . '</p>';
        echo do_shortcode('[upme_login]');
    }
?>

...

<?php
    if ( 'CPT' != get_post_type() || (is_user_logged_in() && array_key_exists( 'comments', $wp_query->query_vars )) ) {
        comment_form();
    }
?>

This code will:

  • Show message "You must be ..." if user is not logged in and is viewing CPT.
  • Show no such message on other post types.
  • Show comment form on CPT only if user is logged in.
  • Show comment form on other post types always.
0

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