0
votes

I want to hide certain categories in my WordPress blog for the public but those that can be viewed by logged in user.

If public goes to visit a restricted category, they should be shown a login box where they must login to view the category

I have the is_user_logged_in function for WordPress but don't know how to use it for this purpose. What should I add to my functions.php?

I have tried this code, but can;t get it to work:

  add_action( 'init', 'check_redirect_page' );

function check_redirect_page() {
    if ( !is_user_logged_in() && !is_category( 177 ) ) {
        wp_redirect( home_url( '/login' ) );
        exit(); 
    }
}

Does anyone have any other suggestions? It just won't work for me :(

2

2 Answers

0
votes

I. Category Templates

You can start building a category template for the category you want to hide:

http://codex.wordpress.org/Category_Templates

E.g. category-slug.php

On this page you can then do something like:

<?php if ( is_user_logged_in() ): ?> 
<?php 
    // start The Loop
    // see http://codex.wordpress.org/The_Loop
    if ( have_posts() ) : while ( have_posts() ) : the_post();
        the_content();
    // etc.
    ?>
    <?php endwhile; else: ?>
    <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
    <?php endif; ?>
<?php else:
        wp_redirect( home_url( '/login' ) );
        exit();     
endif; ?>

http://codex.wordpress.org/Function_Reference/is_user_logged_in http://codex.wordpress.org/Function_Reference/wp_login_url

Further I assume you want to have a modal/popup window for the user to login. For that you can try:

http://wordpress.org/plugins/wp-modal-login/ or http://wordpress.org/plugins/simplemodal-login/ - though I didn't test those.

For a membership plugin... http://wordpress.org/plugins/wp-members/ can you be your friend.

II. Or you can try (the simple way):

<?php 
add_action( 'init', 'check_redirect_page' );

function check_redirect_page() {
    if ( !is_user_logged_in() && is_category( 177 ) ) {
        wp_redirect( home_url( '/login' ) );
        exit(); 
    }
}
?>

As you said this code should reside in your functions.php.

0
votes

For second solution to work, replace [init] with [wp]

New code will be as under:

/**
 * Make category members only and redirect non-members to login page.
 */
add_action( 'wp', 'check_redirect_page' );
function check_redirect_page() {
    if ( !is_user_logged_in() && is_category( 91 ) ) {
        wp_redirect( home_url( '/wp-admin' ) );
        exit(); 
    }
}

Replace 91 with your category ID is and replace /wp-admin with your login for the website.