0

I am using WordPress 3.5, and my blog sites have many registered users. After they log in, I want them to see just their own posts, not others.

So I added this to my functions.php, but I get a blank page.

function only_login_user_post_on_homepage() {
    $current_user = wp_get_current_user();
    query_posts('author=', $current_user -> ID);
}
add_action( 'pre_get_posts', 'only_login_user_post_on_homepage' );

So, I comment out the add_action, then go to index.php, add the same code:

$current_user = wp_get_current_user();
query_posts("author=".$current_user -> ID);

Yeah, got the results, I don't know why? The code are the same, but why I got different result.

2

In your first code example, you hook into the pre_get_posts action, which fires during the main query. But instead of manipulating that query, you trigger another one using query_posts(), which fires the hook again, and you end up with an infinite loop.

With the second code example, you're just overriding the main query after it's occurred. But whilst it works, you've ended up with a redundant, time-consuming query.

You're almost there, and props for your efforts, so let's bring it together:

function wpse_103997_only_posts_by_current_user( $wp_query ) {
    if ( is_user_logged_in() && $wp_query->is_main_query() && $wp_query->is_home() )
        $wp_query->set( 'author', get_current_user_id() );
}
add_action( 'pre_get_posts', 'wpse_103997_only_posts_by_current_user' );
  • thanks man. And which one is better, if I use the first method, that it is to say, everytime and everywhere when I need to query a post, will be invoke this method. But when I use the second method, I just invoke once, just when user visit his/her home page. So the second one is better ? – diligent Jun 24 '13 at 6:46
  • You're right! I've edited my answer, so that it only operates on the main query. Avoid the second method as you end up with unnecessary resource-sapping queries. – TheDeadMedic Jun 24 '13 at 6:50

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.