
Users can extend WordPress functions by using this platform, which allows developers to expand its capabilities. in countless ways. One powerful feature is the ability to perform bulk actions on posts, pages, users, and other content types. While WordPress provides default bulk actions like “Delete” or “Edit,” you can create custom bulk actions tailored to your specific needs. This guide will walk you through the process of adding custom bulk actions to post and user listing screens, handling those actions securely, and providing feedback to users.
1. Understanding Bulk Actions in WordPress
What Are Bulk Actions?
Bulk actions allow administrators to perform operations on multiple items (e.g., posts, users, comments) simultaneously. For example, you can delete 50 posts at once or change the status of 100 users from “Pending” to “Active.”
Why Add Custom Bulk Actions?
- Automate Repetitive Tasks: Save time by performing batch operations.
- Enhance Functionality: Add features specific to your plugin or theme.
- Improve User Experience: Provide tailored actions for your audience.
2. Prerequisites for Custom Bulk Actions
Before diving into code, ensure you have the following:
- Basic knowledge of PHP and WordPress hooks (actions and filters).
- Access to your theme’s functions.php file or a custom plugin.
- A local or staging environment for testing.
3. Step 1: Adding Custom Bulk Actions
For Posts
Using the bulk_actions-{screen_id} Filter
WordPress uses the bulk_actions-{screen_id} filter to modify bulk actions for specific screens. For posts, the screen ID is edit-post.
Example: Adding “Approve” and “Reject” Actions
add_filter('bulk_actions-edit-post', 'add_custom_post_bulk_actions');Â Â
function add_custom_post_bulk_actions($actions) {Â Â
  $actions['approve'] = __('Approve', 'textdomain'); Â
  $actions['reject'] = __('Reject', 'textdomain'); Â
  return $actions; Â
}
Explanation
- add_filter(): Hooks into the bulk_actions-edit-post filter.
- $actions: An array of existing bulk actions.
- Custom Keys: approve and reject are unique identifiers for your actions.
For Users
Using the bulk_actions-users Filter
For the user listing screen, use the bulk_actions-users filter.
Example: Adding “Activate” and “Deactivate” Actions
add_filter('bulk_actions-users', 'add_custom_user_bulk_actions');Â Â
function add_custom_user_bulk_actions($actions) {Â Â
 $actions['activate'] = __('Activate Users', 'textdomain'); Â
 $actions['deactivate'] = __('Deactivate Users', 'textdomain'); Â
  return $actions; Â
}
4. Step 2: Handling Bulk Actions
Processing Selected Items with handle_bulk_actions-{screen_id}
After adding bulk actions, you need to process them. Use the handle_bulk_actions-{screen_id} action hook.
For Posts
Example: Approving or Rejecting Posts
add_action('handle_bulk_actions-edit-post', 'handle_post_bulk_actions', 10, 3);Â Â
function handle_post_bulk_actions($redirect_to, $action, $post_ids) {Â Â
  if ($action === 'approve') { Â
    foreach ($post_ids as $post_id) { Â
      wp_update_post(array( Â
        'ID' => $post_id, Â
        'post_status' => 'publish' Â
      )); Â
    } Â
    $redirect_to = add_query_arg('approved', count($post_ids), $redirect_to); Â
  } elseif ($action === 'reject') { Â
    foreach ($post_ids as $post_id) { Â
      wp_trash_post($post_id); Â
    } Â
    $redirect_to = add_query_arg('rejected', count($post_ids), $redirect_to); Â
  } Â
  return $redirect_to; Â
}
Explanation
- $redirect_to: The URL users are redirected to after the action.
- $action: The selected bulk action (e.g., approve).
- $post_ids: An array of selected post IDs.
For Users
Example: Activating or Deactivating Users
add_action('handle_bulk_actions-users', 'handle_user_bulk_actions', 10, 3);Â Â
function handle_user_bulk_actions($redirect_to, $action, $user_ids) {Â Â
  if ($action === 'activate') { Â
    foreach ($user_ids as $user_id) { Â
      $user = new WP_User($user_id); Â
      $user->set_role('subscriber'); Â
    } Â
    $redirect_to = add_query_arg('activated', count($user_ids), $redirect_to); Â
  } elseif ($action === 'deactivate') { Â
    foreach ($user_ids as $user_id) { Â
      $user = new WP_User($user_id); Â
      $user->remove_role('subscriber'); Â
    } Â
    $redirect_to = add_query_arg('deactivated', count($user_ids), $redirect_to); Â
  } Â
  return $redirect_to; Â
}
Security Best Practices
- Nonce Verification: Ensure authenticated users trigger actions.
- Capability Checks: Restrict actions to users with appropriate permissions.
- Sanitization: Sanitize input data to prevent SQL injection or XSS attacks.
5. Step 3: Displaying Admin Notices
Providing Feedback with admin_notices
After processing bulk actions, display success or error messages using the admin_notices hook.
Example: Post Action Notices
add_action('admin_notices', 'show_post_bulk_action_notices');Â Â
function show_post_bulk_action_notices() {Â Â
  if (!empty($_GET['approved'])) { Â
    $count = intval($_GET['approved']); Â
    echo '<div class="notice notice-success"><p>' . sprintf(__('%d posts approved.', 'textdomain'), $count) . '</p></div>'; Â
  } Â
  if (!empty($_GET['rejected'])) { Â
    $count = intval($_GET['rejected']); Â
    echo '<div class="notice notice-success"><p>' . sprintf(__('%d posts rejected.', 'textdomain'), $count) . '</p></div>'; Â
  } Â
}
Example: User Action Notices
add_action('admin_notices', 'show_user_bulk_action_notices');Â Â
function show_user_bulk_action_notices() {Â Â
  if (!empty($_GET['activated'])) { Â
    $count = intval($_GET['activated']); Â
    echo '<div class="notice notice-success"><p>' . sprintf(__('%d users activated.', 'textdomain'), $count) . '</p></div>'; Â
  } Â
  if (!empty($_GET['deactivated'])) { Â
    $count = intval($_GET['deactivated']); Â
    echo '<div class="notice notice-success"><p>' . sprintf(__('%d users deactivated.', 'textdomain'), $count) . '</p></div>'; Â
  } Â
}
6. Step 4: Testing and Debugging
Testing Your Bulk Actions
- Create Test Data: Add sample posts or users.
- Select Items: Use checkboxes to select multiple items.
- Trigger Actions: Apply your custom bulk actions.
- Verify Results: Check if posts/users are updated and notices appear.
Debugging Tips
- Enable Debugging: Add define(‘WP_DEBUG’, true); to wp-config.php.
- Check Permissions: Ensure the current user has the right capabilities.
- Review Server Logs: Look for PHP errors or warnings.
7. Advanced Use Cases
Custom Post Types
To add bulk actions for custom post types, replace edit-post with edit-{post_type} in the filter.
Example: For a “Books” Post Type
1add_filter('bulk_actions-edit-books', 'add_book_bulk_actions');Â
Bulk Actions with Confirmation Dialogs
Add JavaScript to confirm actions before execution:
add_action('admin_footer', 'add_bulk_action_confirmation');Â Â
function add_bulk_action_confirmation() {Â Â
  echo '<script> Â
    jQuery(document).ready(function($) { Â
      $("select[name=\'action\'], select[name=\'action2\']").on("change", function() { Â
        if ($(this).val() === "approve") { Â
          return confirm("Are you sure you want to approve these posts?"); Â
        } Â
      }); Â
    }); Â
  </script>'; Â
}
8. Troubleshooting Common Issues
Bulk Actions Not Appearing
- Incorrect Hook: Ensure you’re using the right bulk_actions-{screen_id} filter.
- Caching: Clear any caching plugins or server caches.
Actions Not Processing
- Hook Priority: Adjust the priority in add_action() (e.g., 10, 3).
- Capabilities: Verify the user has edit_posts or edit_users capabilities.
Frequently Asked Questions
Conclusion
Custom bulk actions are a game-changer for managing content and users in WordPress. By following this guide, you can automate workflows, enhance functionality, and deliver a polished experience for site administrators. Always prioritize security by validating inputs and restricting access to authorized users. With these tools, you’ll unlock new levels of efficiency and customization in your WordPress projects. For detail you can visit official wordpress develper resource.
About the writer
Hassan Tahir wrote this article, drawing on his experience to clarify WordPress concepts and enhance developer understanding. Through his work, he aims to help both beginners and professionals refine their skills and tackle WordPress projects with greater confidence.