skip to Main Content

I have a question-answer plugin installed so the post type is example.com/question/
I want to show the message just below the post content
it should say "Login or Register" to non logged in users
and welcome to logged-in users

2

Answers


  1. You’re looking for is_user_logged_in();

    Determines whether the current visitor is a logged in user.

    <?php
    
    if ( 'question' === get_post_type() ) {
    
      if ( ! is_user_logged_in() ) {
    
        echo 'An account is required.';
      
      } else {
      
        // ...
      
      };
    
    };
    
    Login or Signup to reply.
  2. Try adding this code to your theme where applicable:

    if (is_user_logged_in()) {
        $current_user = wp_get_current_user();
        echo 'Welcome ' . esc_html($current_user->display_name);
    } else {
        // Save current page url for redirect after login (optional):
        global $wp;
        $redirect = home_url($wp->request);
    
        echo '<a href="' . esc_url(wp_login_url($redirect)) . '">Login or Register</a>';
    }
    

    Also: WordPress has a native function for that – wp_loginout():
    https://developer.wordpress.org/reference/functions/wp_loginout/
    It won’t show the welcome message off the box, but will give logged in users the option to log out instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search