Skip to content

Instantly share code, notes, and snippets.

@BhargavBhandari90
Last active November 27, 2018 17:55
Show Gist options
  • Save BhargavBhandari90/557fd7e1155704e4f268c2016ac536c9 to your computer and use it in GitHub Desktop.
Save BhargavBhandari90/557fd7e1155704e4f268c2016ac536c9 to your computer and use it in GitHub Desktop.
Allow post author to preview non-published post
<?php
/**
* Allow author to preview non published solution.
*
* @param object $posts
* @return object
*/
function preview_post_to_author( $posts ) {
// Get surrent user id.
$current_user_id = get_current_user_id();
// Bail, if non-logged in.
if ( empty( $current_user_id ) ) {
return $posts;
}
global $wp_query, $wpdb;
$post_id = $wp_query->query['p'];
// Bail, if no post id found.
if ( empty( $post_id ) ) {
return $posts;
}
// Get current post author id.
$author_id = get_post_field( 'post_author', $post_id );
// Bail, if no author found.
if ( empty( $author_id ) ) {
return $posts;
}
// Set result for non-adminstrator and solution author.
if ( is_single() &&
$wp_query->post_count == 0 &&
$author_id == $current_user_id &&
! current_user_can( 'adminstrator' ) ) {
$posts = $wpdb->get_results( $wp_query->request );
}
return $posts;
}
add_filter( 'the_posts', 'preview_post_to_author' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment