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

时间:2017-11-26 23:53:29

标签: php wordpress woocommerce product hook-woocommerce

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

  

注意:第580行的D:\ MY-WEBSERVER \ InstantWP_4.3.1 \ iwpserver \ htdocs \ wordpress \ wp-content \ themes \ MYTHEME \ functions.php中的未定义变量:product_id

第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>';
 }
 }
 ?>

有解决这些通知的快速解决方法吗? 非常感谢任何帮助

谢谢

1 个答案:

答案 0 :(得分:2)

在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文件中或任何插件文件中。

经过测试和工作。