Limit custom post type to the authors only on front-end!

Question

I’m trying to limit the custom-post-types to their authors excluding administers on the homepage. This is how the code looks like on the homepage.php

  <?php 

          $args = array(
          'post_type' => 'project',
          'post_status' => 'publish'
          );

          $post_query = new WP_Query ( $args ); ?>

          <?php while($post_query->have_posts()):$post_query->the_post(); ?>

     //display post type content

          <?php endwhile; ?>
<?php wp_reset_postdata(); ?>

I tried using the code below, that almost achieved what i wanted but it is giving an unusual 404 error instead of the homepage for the new users(authors) but works absolutely fine when logged-in as administrator or from old author’s profile before adding this code.

// limit post display to post authors
function limit_post_to_only_author($query) {
    global $current_user;
    if (!current_user_can('manage_options')) {
        $query->set('author', $current_user->ID);
    }
}
add_action('pre_get_posts', 'limit_post_to_only_author');

I’ve posted a question with detailed explanation about the issue that the above code is causing here. but would prefer a solution to limit the post to authors on the frontend…

0
, , , , Rafiq 8 months 0 Answers 105 views 0

Leave an answer