Woocommerce 挂钩函数中的未定义变量 $product_id

Undefined variable $product_id in Woocommerce hooked function

我知道还有一个类似的问题,但我的问题看起来很奇怪。我是 运行 一个 PHP 脚本,并且不断收到如下错误:

Notice: Undefined variable: product_id in D:\ MY-WEBSERVER\InstantWP_4.3.1\iwpserver\htdocs\wordpress\wp-content\themes\MYTHEME\functions.php on line 580

第 580 行如下所示:

 if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) ) echo '<div class="user-bought">&hearts; Hey ' . $current_user->first_name . ', you\'ve purchased this in the past. Buy again?</div>';

这里是完整代码:

 add_action ( 'woocommerce_after_shop_loop_item', 
 'user_logged_in_product_already_bought', 30);

 function user_logged_in_product_already_bought() {
 if ( is_user_logged_in() ) {
 global $product;
 $current_user = wp_get_current_user();
 if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id ) ) echo '<div class="user-bought">&hearts; Hey ' . $current_user->first_name . ', you\'ve purchased this in the past. Buy again?
 </div>';
 }
 }
 ?>

是否有解决这些通知的快速修复方法? 非常感谢您的帮助

谢谢

在 WooCommerce 3+ 中使用此功能的正确方法是:

 add_action ( 'woocommerce_after_shop_loop_item',  'user_logged_in_product_already_bought', 30 );
 function user_logged_in_product_already_bought() {
    if ( ! is_user_logged_in() ) return;

    global $product;

    $current_user = wp_get_current_user();

    if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->get_id() ) ) 
        echo '<div class="user-bought">&hearts; Hey ' . $current_user->first_name . ', you\'ve purchased this in the past. Buy again?</div>';
 }

(第 580 行缺少 $product->get_id() 而不是 未定义 $product_id

或使用 global $post; 应该是:

 add_action ( 'woocommerce_after_shop_loop_item',  'user_logged_in_product_already_bought', 30 );
 function user_logged_in_product_already_bought() {
    if ( ! is_user_logged_in() ) return;

    global $post;

    $current_user = wp_get_current_user();

    if ( wc_customer_bought_product( $current_user->user_email, $current_user->ID, $post->ID ) ) 
        echo '<div class="user-bought">&hearts; Hey ' . $current_user->first_name . ', you\'ve purchased this in the past. Buy again?</div>';
 }

代码进入您的活动子主题(或活动主题)的 function.php 文件或任何插件文件。

已测试并有效。