Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk action for custom post types

I am working on a wordpress project and I want to add the bulk action on my custom post.

I have used Custom Post Type UI plugin for custom post and Advanced Custom Fields plugin for custom fields.

Please suggest me any code or plugin to add bulk action for my custom posts.

Thanks, Aniket.

like image 792
aniket sawal Avatar asked Nov 25 '25 15:11

aniket sawal


1 Answers

Since WordPress 4.7 (released December 2016) it is possible to add custom bulk actions without using JavaScript.

//Hooks
add_action( 'current_screen', 'my_bulk_hooks' );
function my_bulk_hooks() {
    if( current_user_can( 'administrator' ) ) {
      add_filter( 'bulk_actions-edit-post', 'register_my_bulk_actions' );
      add_filter( 'handle_bulk_actions-edit-post', 'my_bulk_action_handler', 10, 3 );
      add_action( 'admin_notices', 'my_bulk_action_admin_notice' );      
    }
}   

//Register
function register_my_bulk_actions($bulk_actions) {
  $bulk_actions['email_to_eric'] = __( 'Email to Eric', 'text_domain');
  return $bulk_actions;
}

//Handle 
function my_bulk_action_handler( $redirect_to, $doaction, $post_ids ) {
  if ( $doaction !== 'email_to_eric' ) {
    return $redirect_to;
  }
  foreach ( $post_ids as $post_id ) {
    // Perform action for each post.
  }
  $redirect_to = add_query_arg( 'bulk_emailed_posts', count( $post_ids ), $redirect_to );
  return $redirect_to;
}

//Notices
function my_bulk_action_admin_notice() {
  if ( ! empty( $_REQUEST['bulk_emailed_posts'] ) ) {
    $emailed_count = intval( $_REQUEST['bulk_emailed_posts'] );
    printf( '<div id="message" class="updated fade">' .
      _n( 'Emailed %s post to Eric.',
        'Emailed %s posts to Eric.',
        $emailed_count,
        'text_domain'
      ) . '</div>', $emailed_count );
  }
}

Note.1: You must use bulk_actions filters when WP_Screen object is defined.That's why I used current_screen action in line 2.

Note.2: if you want to add bulk action to custom page like woocommerce products page just change screen id in line 5 & 6. Ex:
add_filter( 'bulk_actions-edit-product', 'register_my_bulk_actions' );
add_filter( 'handle_bulk_actions-edit-product', 'my_bulk_action_handler', 10, 3 );

More information :

Using Custom Bulk Actions

https://make.wordpress.org/core/2016/10/04/custom-bulk-actions/

like image 57
Themesfa Avatar answered Nov 28 '25 05:11

Themesfa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!