Skip to content

Instantly share code, notes, and snippets.

@MaximeCulea
Created March 12, 2019 18:46
Show Gist options
  • Save MaximeCulea/4589604ad133162b3fc42b05536586aa to your computer and use it in GitHub Desktop.
Save MaximeCulea/4589604ad133162b3fc42b05536586aa to your computer and use it in GitHub Desktop.
Add custom checkbox in admin columns with according ajax event for saving postmeta.
<?php class Post_Column {
function __construct() {
add_filter( 'manage_posts_columns', [ $this, 'columns_head' ] );
add_action( 'manage_posts_custom_column', [ $this, 'columns_content' ], 10, 2 );
add_action( 'admin_footer', [ $this, 'jquery_event' ] );
add_action( 'wp_ajax_newsletter_send_save_meta', [ $this, 'process_ajax' ] );
}
/**
* Add column header
*
* @param $defaults
*
* @author Maxime CULEA
*
* @return mixed
*/
public function columns_head( $defaults ) {
$defaults['newsletter_send'] = 'Newsletter (envoyée)';
return $defaults;
}
/**
* Add the column checkbox
*
* @param $column_name
* @param $post_id
*
* @author Maxime CULEA
*/
public function columns_content( $column_name, $post_id ) {
if ( $column_name == 'newsletter_send' ) {
echo '<input type="checkbox" class="newsletter_send" data-postid="' . $post_id . '" ' . checked( 'yes', get_post_meta( $post_id, 'newsletter_send', true ), false ) . '/>';
}
}
/**
* jQuery event to send the checkbox value
* only for post archive admin page
*
* @author Maxime CULEA
*/
public function jquery_event() {
global $pagenow, $typenow;
if( 'edit.php' !== $pagenow || 'post' !== $typenow ) {
return;
}
echo "<script type='application/javascript'>jQuery(function($){
$('.newsletter_send :checkbox').change(function(){
var checkbox = $(this);
$.ajax({
type: 'POST',
data: {
action: 'newsletter_send_save_meta',
value: checkbox.is(':checked') ? 'yes' : 'no',
post_id: checkbox.attr('data-postid'),
newsletter_send_nonce : '" . wp_create_nonce( "newsletter_send" ) . "'
},
url: ajaxurl,
});
});
});</script>";
}
/**
* Check Ajax event to save the checkbox value as post meta
*
* @author Maxime CULEA
*
* @return bool|int
*/
public function process_ajax() {
check_ajax_referer( 'newsletter_send', 'newsletter_send_nonce' );
if ( empty( $_POST['post_id'] ) ) {
wp_die( -1, 403 );
}
return update_post_meta( (int) $_POST['post_id'], 'newsletter_send', (string) $_POST['value'] );
}
}
new Post_Column();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment