I am trying to build a system that lists users posts only (that I have managed to code) but also restricts users from seeing eachothers posts.

If user A has his post under: domain.com/category/postA and he will pass this URL to user B, User B will either be redirected to main page or will be shown 404.

So for achives I do:

<?php if (is_user_logged_in()): ?> 

<?php get_header(); ?>

// code of the loop

<?php get_footer(); ?>

<?php else: ?>
    <?php header( 'Location: http://www.domain.com' ) ; ?>
<?php endif; ?>

And this works fine, but I am struggling with protecting users post.

I tried putting this code to functions. But it looks like is_single doesn't work here. Without is_single protection works (404 is shown to userB), but it also hides widget for user A.

function __set_all_posts_for_author( $query ) {
  if (is_single()) {
    $current_user = wp_get_current_user();
    $query->set( 'author', $current_user->ID );
add_action( 'pre_get_posts', '__set_all_posts_for_author' );

Is there any better way (more secure) to achieve this goal ?

  • what you mean by (more secure) ? – shyammakwana.me Nov 24 '14 at 11:55
  • Firstly I would like it to work, and then I would like to check with You guys if you can see potential weakness of such a method. I guess what I mean is to check my logic ... – Mastafu Nov 24 '14 at 12:22
  • as I think you are getting ID from core functions, there is no any weakness, unless you get any input from user. – shyammakwana.me Nov 27 '14 at 5:59
  • Thx for checking. – Mastafu Nov 28 '14 at 8:25

Try this code: (edited code a little)

add_action( 'template_redirect', 'my_page_template_redirect' );
function my_page_template_redirect() {
    global $post;
    if( is_user_logged_in() ) {
        if( is_single() ){
            if( $post->post_author != get_current_user_id() ){
                wp_redirect( 'IN ANY PAGE' );
        wp_redirect( 'IN ANY PAGE' );
| improve this answer | |

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.