I want to hook my custom function whenever any product assigned as featured product or removed from featured product.
I have found that featured product call WC_AJAX on WooCommerce and it don't have any action hook.
Class WC_AJAX woocommerce/includes/class-wc-ajax.php
line 505
/**
* Toggle Featured status of a product from admin.
*/
public static function feature_product() {
if ( current_user_can( 'edit_products' ) && check_admin_referer( 'woocommerce-feature-product' ) && isset( $_GET['product_id'] ) ) {
$product = wc_get_product( absint( $_GET['product_id'] ) );
if ( $product ) {
$product->set_featured( ! $product->get_featured() );
$product->save();
}
}
wp_safe_redirect( wp_get_referer() ? remove_query_arg( array( 'trashed', 'untrashed', 'deleted', 'ids' ), wp_get_referer() ) : admin_url( 'edit.php?post_type=product' ) );
exit;
}
Any advice how can i hook my custom function?
In woocommerce/includes/class-wc-ajax.php from line 122 ... 179 it says:
$ajax_events = array(
'feature_product',
'mark_order_status',
...
);
foreach ( $ajax_events as $ajax_event ) {
add_action( 'wp_ajax_woocommerce_' . $ajax_event, array( __CLASS__, $ajax_event ) );
}
So with that knowledge we can assign our custom function to the hook
function my_callback_function () {
// Do something
}
add_action( 'wp_ajax_woocommerce_feature_product', 'my_callback_function', 5 );
Explanation
Point 1
Hook priority of 5 used - for this ajax call our action has to come before the woocommerce action because the woocommerce action does a redirect.
The default priority is 10
Point 2
wp_ajax_
This hook allows you to create custom handlers for your own custom AJAX requests. The
wp_ajax_
hook follows the formatwp_ajax_$youraction
, where$youraction
is your AJAX request’s ‘action’ property.The
wp_ajax_
hook only fires for logged-in users.If you need to also listen for Ajax requests that don’t come from logged-in users.
wp_ajax_nopriv_
This hook is functionally the same as
wp_ajax_(action)
, however it is used to handle AJAX requests on the front-end for unauthenticated users, i.e. whenis_user_logged_in()
returns false. Unlikewp_ajax_(action)
the ajaxurl javascript global property will not be automatically defined and must be included manually or by usingwp_localize_script()
withadmin_url( ‘admin-ajax.php’ )
as the data.