Preview others posts without edit

Preview Others Posts Without Editing

Preview Others Posts

You can preview others not published yet posts in case you can edit them only. This is WordPress behavior by default. Suppose, you decided to change that, and give some users or role ability to read others posts in read-only mode, not giving them ‘edit-others-posts’ capability.
You will need to add a new user capability, modify one file from WordPress core and add little piece of code to your theme functions.php file. Are you ready? Let’s go!

  • 1st of all, download and install User Role Editor plugin. Add new ‘preview_others_posts’ capability and turn it on for selected users or role.
  • 2nd, look into function get_posts() of wp-includes/query.php WordPress core file at line #2670:
    2670
    2671
    2672
    2673
    2674
    
      // User must have edit permissions on the draft to preview.
      if ( ! current_user_can($edit_cap, $this->posts[0]->ID)) {
    	$this->posts = array();
      } else {
    	$this->is_preview = true;

    And replace it to this

    2670
    2671
    2672
    2673
    2674
    
      // User must have edit permissions on the draft to preview.
      if ( ! current_user_can($edit_cap, $this->posts[0]->ID) && !current_user_can('preview_others_posts')) {  // modified by shinephp
    	$this->posts = array();
      } else {
    	$this->is_preview = true;

    This way WordPress will allow preview pending posts not only users, who can edit them, but users, who have not ‘edit_others_posts’ capability, but can preview others posts.

  • Negative side is that you need to change wp-includes/query.php after every WordPress update. If you find a way to achieve this task without editing WordPress core, please share that.

  • 3rd and final part, add code below to your current theme functions.php file:
      function add_preview_post_row_actions($actions) {
        global $post;
     
      $post_type_object = get_post_type_object( $post->post_type );
      $can_edit_post = current_user_can( $post_type_object->cap->edit_post, $post->ID );
     
      if (!$can_edit_post && $post->post_status=='pending') {
        $title = _draft_or_post_title();
        $actions['view'] = '<a href="' . esc_url( add_query_arg( 'preview', 'true', get_permalink( $post->ID ) ) ) . '" title="' . esc_attr( sprintf( __( 'Preview &#8220;%s&#8221;' ), $title ) ) . '" rel="permalink">' . __( 'Preview' ) . '</a>';
      }
     
      return $actions;
     
      }
     
    if (current_user_can('preview_others_posts')) {
      add_filter('post_row_actions', 'add_preview_post_row_actions');
    }

    This way we add ‘Preview’ link for others posts in the ‘penging’ state.

Negative side is that you should to update wp-includes/query.php file after every WordPress update. If you find a way to fulfill this task without WordPress core editing, please share it. Thanks.

Tags: , , ,