将变量从过滤器传递到另一个函数

时间:2019-06-13 08:11:55

标签: php wordpress woocommerce

我需要将在过滤器中存储为var的产品ID传递给另一个函数。

我尝试了此操作,但未通过ID:

PHP

$has_option_id = null;

function wc_add_to_cart_message_filter($message, $product_id = null) {
    $GLOBALS['has_option_id'] = $product_id;
    return $message;
}
add_filter ( 'wc_add_to_cart_message', 'wc_add_to_cart_message_filter', 10, 2 );

function above_cart_js() {
    $product_id = $GLOBALS['has_option_id'];
    echo $product_id; // Outputs NULL (nothing)
}
add_action ( 'woocommerce_before_cart', 'above_cart_js', 5 );

是否可以将ID传递给其他功能?

1 个答案:

答案 0 :(得分:1)

由于给定的操作和过滤器不会在同一个HTTP请求中失效,因此它们不能相互全局变量。其中一个通常由AJAX运行,另一个位于“购物车模板挂钩”中。因此,您可以通过Cookie存储来实现。首先,商店只是将产品ID添加到Cookie中,然后从那里获取它。

function wc_add_to_cart_message_filter($message, $product_id = null) {
  setcookie('just_added_product', array_keys($product_id)[0], time() + (600), "/"); 
  return $message;
}
add_filter ( 'wc_add_to_cart_message_html', 'wc_add_to_cart_message_filter', 10, 2 );

function above_cart_js() {
  echo $_COOKIE["just_added_product"]; 
}
add_action ( 'woocommerce_before_cart', 'above_cart_js', 5 );
相关问题