Redirect After Order Status
December 18, 2024 · AI Conversations
1. **Create a Custom Function**: You’ll need to create a function that listens for the order status change and performs the redirect.
2. **Add the Function to Your Theme or Plugin**: You can add the following code to your theme's `functions.php` file or to a custom plugin.
Here’s an example of how to do this:
add_action('woocommerce_order_status_changed', 'custom_redirect_after_order_status_change', 10, 4);
function custom_redirect_after_order_status_change($order_id, $old_status, $new_status, $order) {
// Check if we are in the admin area and the request is a POST request
if (is_admin() && isset($_POST['post_type']) && $_POST['post_type'] === 'shop_order') {
// Get the URL of the custom page
$redirect_url = admin_url('admin.php?page=your_custom_page_slug'); // Change 'your_custom_page_slug' to your desired page slug
// Redirect
wp_safe_redirect($redirect_url);
exit; // Always call exit after a redirect
}
}
### Explanation:
– **Hook**: The function `custom_redirect_after_order_status_change` is hooked to `woocommerce_order_status_changed`, which triggers whenever an order status changes.
– **Condition**: The code checks if the request is coming from the admin area and whether the post type is `shop_order`.
– **Redirect**: It uses `wp_safe_redirect()` to send the user to your custom page and then calls `exit` to stop further execution.
### Custom Page:
Make sure that the page you want to redirect to exists. You can create a custom admin page by using the `add_menu_page` function in your plugin or theme.
Here’s a brief example of how to create a custom admin page:
add_action('admin_menu', 'custom_admin_menu');
function custom_admin_menu() {
add_menu_page(
'Custom Page Title', // Page title
'Custom Menu', // Menu title
'manage_options', // Capability
'your_custom_page_slug', // Menu slug
'custom_page_callback', // Function to display the page content
'dashicons-admin-generic' // Icon
);
}
function custom_page_callback() {
echo '<h1>Custom Page Content</h1>';
// Your custom page content goes here
}
### Usage:
– Replace `'your_custom_page_slug'` with the actual slug of your custom admin page.
– Adjust any other details according to your needs.
This setup will redirect the user to the specified custom page whenever an order status is changed in the WooCommerce admin.