1

On my site I have a number of post category archive pages. What I would like to do is set it up so that when links to specific posts are clicked on these pages the user is sent to the post only if they are logged in. Otherwise they would be sent to the login/sign up page.

I don't want the articles themselves to be restricted, meaning if somebody found a link outside my site to the post they would be able to view it without logging in. I only want access restricted when the user is coming directly from an internal archive page.

Thank you for your help.

2 Answers 2

3

You might start by looking at the is_user_logged_in() pluggable function.

https://developer.wordpress.org/reference/functions/is_user_logged_in/

This is basically two lines:

$user = wp_get_current_user();
return $user->exists();

In your case, wrap the links inside the curly braces of a conditional.

if ( is_user_logged_in() ) {

    // link
}
5
  • Thanks. So using this could I add some code in the archive template file which replaces the links to each post with a link to the login page if the user isn't logged in? Commented May 5, 2016 at 19:56
  • Yes indeed you could. You might also want to detect for search engines, though, so that they get the proper links.
    – Tim Malone
    Commented May 5, 2016 at 21:44
  • Thanks for pointing that out. How would I go about detecting search engines? Commented May 5, 2016 at 21:50
  • If you could show me how to apply search engine detection to the code in my answer below it would be very helpful. Commented May 5, 2016 at 21:59
  • That would probably be a separate question :) Best to ask that one on StackOverflow because it's not specifically WP related. Do a search on StackOverflow first because it's probably been answered before.
    – Tim Malone
    Commented May 5, 2016 at 22:18
1

I've worked it out with thanks to LPH for pointing me in the right direction.

I added this to functions.php:

function login_page_url() {
    global $loginurl;
    $loginurl = "login page url";
    echo $loginurl;
}

And this to category.php, where the link to the post goes:

<a href="<?php if ( is_user_logged_in() ) { echo get_permalink(); } else { echo login_page_url(); } ?>">

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.