【问题标题】:Get the customer user_id in Woocommerce email footer template在 Woocommerce 电子邮件页脚模板中获取客户 user_id
【发布时间】:2018-04-28 08:21:04
【问题描述】:

我正在尝试在 woocommerce 自定义电子邮件模板中获取 current_user_id,但它返回 0。有谁知道如何在 wordpress 的电子邮件模板中获取 user_id。当我在任何 php 模板中使用此代码时,我都会得到用户 ID。

下面是我的代码:

<?php global $current_user;
      get_currentuserinfo();
      echo '<h4>Your code:</h3>' . $current_user->ID . '';
?>

这里是完整的模板代码链接: email-template-code

【问题讨论】:

  • 单个函数可以获取id,所以不需要全局;变量和 get_currentuserinfo() 函数。只需使用 get_current_user_id()。如果它也不起作用,那么您需要提供该模板函数的完整代码。可能是您在该代码的另一部分做错了什么。
  • @Elvin85 好的,试试吧。
  • @Elvin85 它返回 0。我现在正在添加完整的文件代码。
  • @Elvin85 这里是代码链接codeshare.io/GqXW1A
  • 那里似乎没问题。这个模板文件在哪里?在 woocommerce/templates 或 your_theme/woocommerce/templates 中?可能只是混淆了,您编辑了错误的文件。例如,尝试将“Your Code”更改为“Your Codeeee”,并确保更改对发送的邮件产生影响。 ......还有更多的事情:如果你称它为服务器端(使用 CURL,CRON f.e.)它当然不会提供任何用户 ID。

标签: php wordpress woocommerce userid email-notifications


【解决方案1】:

您无法在 woocommerce 电子邮件模板中获取当前用户,但您可以从订单中获取客户用户 ID

要获取客户的User ID,可以在$GLOBAL变量中设置并获取一些数据:

  • 设置数据 - 在您的活动主题function.php 文件上:
add_action( 'woocommerce_email_header', 'wc_email_user_id', 10, 2 );
function wc_email_user_id( $email_heading, $email ) {
    // Set global variable data: user ID and Order ID
    $GLOBALS['emails_custom_data'] = array(
        'user_id' => get_post_meta( $email->object->ID, '_customer_user', true ), // Set the user ID
        'order_id' => $email->object->ID, // Set the Order ID
    );
}
  • 获取数据 - 之后在您的模板文件中:
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

## --- Your custom Code start here --- ##

$refNameGlobalsVar = $GLOBALS; // Get the data
$custom_data = $refNameGlobalsVar['emails_custom_data']; // Set the data in a variable

$user_id = $custom_data['user_id']; // Get the user ID
$order_id = $custom_data['order_id']; // Get the order ID (in case of…)

// Testing output
echo '<p>The user ID is '.$user_id.' | From the Order ID: '.$order_id.'</p>';

## --- End of custom code --- ##

?>

此代码已经过测试并且可以工作

【讨论】:

    【解决方案2】:

    我认为您应该像在电子邮件模板中使用的那样使用 wordpress 钩子:

    apply_filters( 'woocommerce_email_footer_text', get_option( 'woocommerce_email_footer_text' )
    

    而不是直接这样写

    global $current_user;
    get_currentuserinfo();
    echo '<h4>Your code:</h3>' . $current_user->ID . '';
    

    你可以像这样应用过滤器

    global $current_user;
    apply_filters( 'woocommerce_custom_template_email', $current_user->ID );
    

    当触发负责发送电子邮件的电子邮件功能时,您可以像这样使用 add_filter

    add_filters( 'woocommerce_custom_template_email', 'custom_email_function' );
    function custom_email_function($user_id) {
        global $current_user;
        $user_id = $current_user->ID;
        return $user_id;
    }
    

    也许通过这种方式您可以获得当前用户ID。还要确保您正在尝试获取已登录用户的当前用户 ID。

    【讨论】:

    • 我使用了这段代码,但它使网站关闭 http 500 错误。
    猜你喜欢
    • 2019-08-05
    • 2014-05-17
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多