Comments On/Off Switch in the Posts List
Adds a column to the Posts list with a switch that opens or closes comments on each post in one click, without opening the editor or Quick Edit.
Opens WPIDE on
Code
add_filter( 'manage_post_posts_columns', function ( $columns ) {
$columns['wpide_comments_open'] = 'Comments';
return $columns;
} );
add_action( 'manage_post_posts_custom_column', function ( $column, $post_id ) {
if ( 'wpide_comments_open' !== $column ) {
return;
}
$open = 'open' === get_post_field( 'comment_status', $post_id );
printf(
'<button type="button" class="button button-small wpide-comment-toggle" data-id="%d" aria-pressed="%s">%s</button>',
(int) $post_id,
$open ? 'true' : 'false',
$open ? 'Open' : 'Closed'
);
}, 10, 2 );
add_action( 'wp_ajax_wpide_comment_toggle', function () {
check_ajax_referer( 'wpide_comment_toggle', 'nonce' );
$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
wp_send_json_error( null, 403 );
}
$status = 'open' === get_post_field( 'comment_status', $post_id ) ? 'closed' : 'open';
wp_update_post( array( 'ID' => $post_id, 'comment_status' => $status ) );
wp_send_json_success( array( 'open' => 'open' === $status ) );
} );
add_action( 'admin_footer-edit.php', function () {
?>
<script>
document.addEventListener( 'click', function ( event ) {
var button = event.target.closest( '.wpide-comment-toggle' );
if ( ! button ) { return; }
button.disabled = true;
var body = new FormData();
body.append( 'action', 'wpide_comment_toggle' );
body.append( 'nonce', <?php echo wp_json_encode( wp_create_nonce( 'wpide_comment_toggle' ) ); ?> );
body.append( 'post_id', button.dataset.id );
fetch( ajaxurl, { method: 'POST', credentials: 'same-origin', body: body } )
.then( function ( r ) { return r.json(); } )
.then( function ( r ) {
button.disabled = false;
if ( ! r.success ) { return; }
button.textContent = r.data.open ? 'Open' : 'Closed';
button.setAttribute( 'aria-pressed', r.data.open ? 'true' : 'false' );
} );
} );
</script>
<?php
} );
Notes
Only users who can edit the post can flip the switch.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.