0

I'm using next_post_link() and previous_post_link() in my theme. I excluded my password protected posts from the loop. They only appear if you enter the URL of this specific post.

But, the problem is that I have next_post_link() and previous_post_link() appearing in every single post. So when I'm in a post that is succeeded or preceded by a password protected post, the password protected post appears in the pagination.

I need to exclude all my password protected post of appearing when using the two aforementioned functions.

I tried using the filters and functions provided in the codex but none of them work the way I need.

1 Answer 1

2

The function next_post_link() allow excludes, with the parameter excluded_terms. Add a list of the IDs of the password protected posts to this param.

You get a list of all password protected posts with the follow example via DB select.

$password_pages = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND post_password !=''");

Alternative can you use a hook to filter the password protected post from the loop. Also a example below, that works on the single and page view of the front end.

// Filter to hide protected posts
function exclude_protected($where) {
    global $wpdb;
    return $where .= " AND {$wpdb->posts}.post_password = '' ";
}

// Decide where to display them
function exclude_protected_action($query) {
    if( !is_single() && !is_page() && !is_admin() ) {
        add_filter( 'posts_where', 'exclude_protected' );
    }
}

// Action to queue the filter at the right time
add_action('pre_get_posts', 'exclude_protected_action');
2
  • I'm using the first option with excluded_terms. But the thing is, when the post is in between two password protected posts, it shows the password protected posts anyway. Lets say, post 1 and 3 have password protection, so when I'm in post 2, it shows post 1 and 3.
    – Sebastian
    Apr 10, 2015 at 18:38
  • And you exclude this also on all templates, there use the next post function? Like the single.php
    – bueltge
    Apr 10, 2015 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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