I’m using the category template to list a series of custom posts, each of which lists a link to document. Some documents are public and some are private. Currently, if the post is public, the link is displayed; but if the link is private, I’m echoing a statement “Private resource — please log in to read.”
I want to make the words “log in” a link that sends any non-logged-in user to the login page and then redirects the user back to this page. But I haven’t been able to make it work. I thought maybe auth_redirect() is the way to go, but maybe I’m off base on that.
Here’s a somewhat simplified version of the loop as it currently stands.
if ( have_posts() ) :
while ( have_posts() ) : the_post();
// the loop
$private = get_post_custom_values('private'); // read custom field
if (isset($private[0]) && $private[0] == 'yes' ) { // if the post is private
if ( is_user_logged_in() ) {// and if the user is logged in
// display private post ?>
<div>
<h4><?php the_title(); ?></h4>
<?php get_post_custom_keys();?>
<p><?php the_content(); ?></p>
<p><a href="<?php echo get_post_meta($post->ID, "resourcelink", true); ?>">Resource Link</a></p>
<?php if (get_post_meta($post->ID, "private", true)==yes) {?>
<p class="private">This document private.</p>
<?php } ?>
</div>
<?php }
else { // if the user is not logged in
// want make the a login link, with redirect back to this page
// but now just tells user to log in ?>
<div>
echo the_title('<h4>','</h4>');
get_post_custom_keys();?>
<p><?php the_content(); ?></p>
<?php echo '<p>Private resource — please log in to read.</p>';
}
}
else { // if the post is public
// display public post, for every visitor ?>
<div>
<h4><?php the_title(); ?></h4>
<?php get_post_custom_keys();?>
<p><?php the_content(); ?></p>
<p><a href="<?php echo get_post_meta($post->ID, "resourcelink", true); ?>">Resource Link</a></p>
</div>
<?php }
endwhile;
endif;
?>
If the user is not logged in, you could just display that they don’t have permissions and
wp_login_form()
which handles the redirects and all. Reference.