Skip to content

Instantly share code, notes, and snippets.

@nacin
Created June 1, 2011 06:41
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nacin/4f4bc2d18a66c1eff93a to your computer and use it in GitHub Desktop.
Save nacin/4f4bc2d18a66c1eff93a to your computer and use it in GitHub Desktop.
Allow Linking to Private Posts
<?php
/*
* Plugin Name: Allow Linking to Private Posts
* Description: Allows direct linking to private posts without authentication.
* Author: Nacin
* Version: 0.1-beta
*/
class Nacin_Links_Private_Posts {
private $restore = null;
private $comment_on_private = false;
function __construct() {
add_filter( 'posts_results', array( &$this, 'post_results' ), 10, 2 );
add_action( 'pre_comment_on_post', array( &$this, 'pre_comment_on_post' ) );
add_filter( 'pre_comment_approved', array( &$this, 'pre_comment_approved' ) );
}
function post_results( $posts, $wp_query ) {
// Make sure this is the main query.
if ( $wp_query !== $GLOBALS['wp_the_query'] )
return $posts;
// Need to be a single post, and not the comments feed.
if ( ! $wp_query->is_single || $wp_query->is_feed )
return $posts;
// If the post status is private, fake it.
if ( $posts[0]->post_status == 'private' ) {
$posts[0]->post_status = 'publish';
// Robots noindex, nofollow.
add_filter( 'pre_option_blog_public', '__return_zero' );
// Add a little warning.
add_filter( 'the_content', array( &$this, 'the_content' ), 11 );
// Restore.
add_filter( 'the_posts', array( &$this, 'the_posts' ) );
$this->restore = $posts[0];
}
return $posts;
}
function the_posts( $posts ) {
if ( $posts[0] === $this->restore ) {
$posts[0]->post_status = 'private';
$this->restore = null;
}
return $posts;
}
function the_content( $content ) {
$warning = '<hr/><p><strong>Warning: This post is private.
It can only be accessed by the URL.</strong></p><hr/>';
return $warning . $content;
}
function pre_comment_on_post( $post_id ) {
global $post;
if ( $post->post_status == 'private' ) {
$this->comment_on_private = true;
$post->post_status = 'publish';
}
}
function pre_comment_approved( $approved ) {
if ( $this->comment_on_private )
$approved = 0;
return $approved;
}
}
new Nacin_Links_Private_Posts;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment