You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce产品切换精选状态时触发自定义函数的钩子实现咨询

WooCommerce 产品精选状态切换挂载自定义函数可行方案

方案1:使用WooCommerce原生产品属性变更钩子(最推荐,无侵入)

WooCommerce的WC_Product类所有属性的setter方法都会自动触发对应的动作钩子,设置精选状态的set_featured方法对应钩子为woocommerce_product_set_featured,可以直接挂载自定义函数,不管是AJAX切换、后台编辑页修改、还是代码手动调用修改精选状态都会触发,覆盖全场景。
示例代码:

add_action('woocommerce_product_set_featured', 'custom_after_featured_toggle', 10, 2);
function custom_after_featured_toggle($product_id, $featured_status) {
    // $featured_status为布尔值,true代表设为精选,false代表取消精选
    // 此处填写自定义逻辑
}

如果需要仅在后台AJAX切换的场景触发,可以在函数内增加请求判断:

add_action('woocommerce_product_set_featured', 'custom_after_featured_toggle_ajax_only', 10, 2);
function custom_after_featured_toggle_ajax_only($product_id, $featured_status) {
    // 判断是否为后台AJAX切换精选的请求
    if (!defined('DOING_AJAX') || !DOING_AJAX || !isset($_REQUEST['action']) || $_REQUEST['action'] !== 'woocommerce_feature_product') {
        return;
    }
    // 此处填写自定义逻辑
}

方案2:替换默认AJAX回调(适合需要完全控制流程的场景)

WooCommerce的AJAX接口是通过WordPress原生wp_ajax_{action}钩子注册的,你可以先移除默认的回调,再挂载自定义回调,在里面插入自定义逻辑后复用原有核心代码即可。
示例代码:

add_action('wp_ajax_woocommerce_feature_product', 'custom_replace_feature_product_callback', 0);
function custom_replace_feature_product_callback() {
    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 ) {
            $old_status = $product->get_featured();
            $new_status = !$old_status;
            $product->set_featured( $new_status );
            $product->save();
            
            // 此处插入自定义逻辑
            custom_your_featured_handle_function($product->get_id(), $old_status, $new_status);
        }
    }

    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;
}

方案3:监听文章元数据变更钩子(兼容3.0以下旧版WooCommerce)

如果使用的是3.0以下的旧版WooCommerce,精选状态存储在文章元数据中,可以监听update_post_meta钩子判断元数据键实现触发。
示例代码:

add_action('update_post_meta', 'custom_featured_meta_change', 10, 4);
function custom_featured_meta_change($meta_id, $post_id, $meta_key, $meta_value) {
    // 旧版WooCommerce精选状态存储在_visibility元数据,值为featured代表精选
    if ($meta_key !== '_visibility') {
        return;
    }
    $product = wc_get_product($post_id);
    if (!$product) {
        return;
    }
    $featured_status = $meta_value === 'featured';
    // 此处填写自定义逻辑
}

内容的提问来源于stack exchange,提问作者Vicky P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:42:01