0

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...

2
  • The code is working as it is intended , The home page is not created by any of the authors , so it restricts them from viewing it . As admins are exempted they can view all pages including home page . Try the code below ( it works in twentytwenty )
    – Anoop D
    Commented Jun 10, 2020 at 5:12
  • ` function app_output_buffer() { ob_start(); } add_action('init', 'app_output_buffer'); function set_only_author($query) { if (!current_user_can('manage_options')) { $query->set('author', get_current_user_id()); if(is_404()) { wp_redirect(get_author_posts_url( get_current_user_id())); } } } add_action('pre_get_posts', 'set_only_author'); `
    – Anoop D
    Commented Jun 10, 2020 at 5:14

0

Your Answer

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