public
Last active

Anonymous comments per post

  • Download Gist
anonymous-comments-per-post.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
<?php
/**
* Plugin Name: Anonymous comments per post
* Plugin URI: http://wordpress.stackexchange.com/q/73788/73
* Version: 2012.11.24
* Author: Thomas Scholz
* Author URI: http://toscho.de
* Licence: MIT
* License URI: http://opensource.org/licenses/MIT
*/
 
add_action( 'post_comment_status_meta_box-options', 'acpp_checkbox' );
/**
* Print a checkbox into the comment status metabox.
*
* @wp-hook post_comment_status_meta_box-options
* @param object $post
* @return void
*/
function acpp_checkbox( $post )
{
$key = '_allow_anonymous_comments';
$current = get_post_meta( $post->ID, $key, TRUE );
 
printf(
'<br /><label for="%1$s">
<input type="checkbox" id="%1$s" name="%1$s" class="selectit" %2$s/> %3$s
</label>',
$key,
checked( 1, $current, FALSE ),
apply_filters( 'acpp_metabox_label', 'Allow anonymous comments.' )
);
}
 
add_action( 'save_post', 'acpp_save' );
/**
* Save the checkbox value as number
*
* @wp-hook save_post
* @param int $post_id
* @param object $post
* @return void
*/
function acpp_save( $post_id, $post )
{
// AJAX autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
 
// Some other POST request
if ( ! isset ( $_POST['post_type'] ) )
return;
 
// Missing capability
if ( ! current_user_can( 'edit_' . $_POST['post_type'], $post_id ) )
return;
 
$key = '_allow_anonymous_comments';
 
// Checkbox successfully clicked
if ( isset ( $_POST[ $key ] ) and 'on' === strtolower( $_POST[ $key ] ) )
return update_post_meta( $post_id, $key, 1 );
 
// Checkbox deselected
delete_post_meta( $post_id, $key );
}
 
add_filter( 'pre_option_comment_registration', 'acpp_comment_reg_filter' );
/**
* Trick the registration checks on front-end
*
* Important: If we return FALSE, the filter will be effectively ignored.
* It has to be any other value.
*
* @wp-hook pre_option_comment_registration
* @return bool|int
*/
function acpp_comment_reg_filter()
{
if ( is_admin() )
return FALSE;
 
$key = '_allow_anonymous_comments';
$post_id = 0;
 
// Only available on wp-comments-post.php, not on regular post pages.
if ( isset( $_POST['comment_post_ID'] ) )
$post_id = (int) $_POST['comment_post_ID'];
 
//
$post = get_post( $post_id );
$open = get_post_meta( $post->ID, $key, TRUE );
 
if ( 1 == $open )
return 0;
 
return FALSE;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.