1

I have a site with a listings page (https://gymkoi.com/class-listings/) and all I'm trying to do is redirect a user who is not logged in to my login page (https://gymkoi.com/login/) before they can view an individual listing. If they are logged in then they can go straight to the individual listing.

I'd like to do this without having to use a plugin as this seems like it should be a relatively easy thing to do via php.

Thanks!

  • Quick question, after they login are they then directed to a page of listings or a specific listing? – Tony Djukic May 21 at 20:12
  • eventually i'd like them to go to the listing they clicked on – Jon Timms May 21 at 21:41
1

You could set up a child theme, and in the single-listing.php template, add conditions around the current code.

<?php
// If the user is not logged in, redirect
if ( false == is_user_logged_in() ) {
    wp_redirect( wp_login_url() );
    exit;
}
// Else the user is logged in; show the listing
else {
    // Paste the regular template code here
}
?>

Everything else will remain public, while just the individual listings will force the user to be logged in before they can view the content. (This will also prevent search engines from seeing the content, so bear that in mind.)

| improve this answer | |
  • This is great thanks! One question (I'm a little new to php). How do I redirect to a custom login page vs the wp login page? I think wp_login_url() is sending me to the wp login page. How do I send them to gymkoi.com/login? Thanks so much! – Jon Timms May 21 at 19:18
  • That's correct - just replace wp_login_url() with '/' in quotes. – WebElaine May 21 at 19:44
  • 1
    Better yet, add a login form right inside the single-listing.php for when a user is not logged in. <?php wp_login_form(); ?> - developer.wordpress.org/reference/functions/wp_login_form – Travis Pflanz May 21 at 19:45
  • thank you very much for the help, will test these out. – Jon Timms May 21 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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