在另一个函数中访问一个函数的变量

时间:2019-04-19 10:09:15

标签: php wordpress woocommerce hook-woocommerce

我在第一个函数中声明了一个全局变量,而我试图在第二个函数中访问该变量。但这不起作用。 变量名称为lastwarn

$unique_code

1 个答案:

答案 0 :(得分:1)

尝试在任何函数外部声明变量。同时在两个函数中都使用global关键字。此外,请确保在laksh_add_content_specific_email之前调用laksh_add_content_specific_email2

$unique_code = 0;

add_action( 'woocommerce_email_before_order_table', 'laksh_add_content_specific_email', 20, 4 );
function laksh_add_content_specific_email( $order, $sent_to_admin, $plain_text, $email ) {
    global $unique_code;
    $unique_code = mt_rand(100000, 999999);
}

add_action( 'woocommerce_email_after_order_table', 'laksh_add_content_specific_email2', 20, 4 );
function laksh_add_content_specific_email2( $order, $sent_to_admin, $plain_text, $email ) {
    global $unique_code;

    if ( $email->id == 'customer_processing_order' ) {
        echo '<h2 class="email-upsell-title">Redeem Code</h2>';
        echo '<p class="email-upsell-p"><strong>' . $unique_code . '</strong></p>';
        echo '<p class="email-upsell-p">Please show this code at the reception when you visit us to redeem your gift card.</p>';
    }
}