在WooCommerce中添加隐藏的结帐字段? [英] Adding a hidden checkout field in WooCommerce?

查看:112
本文介绍了在WooCommerce中添加隐藏的结帐字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想包含指向通过WooCommerce提交结帐表格的当前用户的个人资料的链接。

I want to include a link to a profile of the current user who submitted a checkout form through WooCommerce.

也就是说,自动放置当前用户的作者链接在隐藏字段中是这样的: example.com/author/username

That is, to place automatically a current user’s author link like this in the hidden field: example.com/author/username

我想添加一个结帐表单中的隐藏字段。因此,要获取链接,我会这样写:

I want to achieve this by adding a hidden field in checkout form. So to get a link I would write something likes this:

<?php

$currentUser = get_current_user_id();

$user = get_user_by( 'id', $currentUser );

$userUrl = get_bloginfo( 'home' ) . '/author/' . $user->user_login;

echo $userUrl;
?>

我的问题是如何在结帐表单中创建这种类型的隐藏字段?

My question is how can I create this type of hidden field in checkout form?

推荐答案

woocommerce_after_order_notes 动作挂钩中附加了自定义功能,您还可以使用此用户作者链接直接输出一个隐藏字段作为隐藏值,当客户下订单时,该字段将与所有结帐字段同时提交。

With a custom function hooked in woocommerce_after_order_notes action hook, you can also directly output a hidden field with this user "author link" as a hidden value, that will be submitted at the same time with all checkout fields when customer will place the order.

这是代码:

add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_hidden_field', 10, 1 );
function my_custom_checkout_hidden_field( $checkout ) {

    // Get an instance of the current user object
    $user = wp_get_current_user();

    // The user link
    $user_link = home_url( '/author/' . $user->user_login );

    // Output the hidden link
    echo '<div id="user_link_hidden_checkout_field">
            <input type="hidden" class="input-hidden" name="user_link" id="user_link" value="' . $user_link . '">
    </div>';
}

然后,您需要按以下方式保存此隐藏字段:

Then you will need to save this hidden field in the order, this way:

add_action( 'woocommerce_checkout_update_order_meta', 'save_custom_checkout_hidden_field', 10, 1 );
function save_custom_checkout_hidden_field( $order_id ) {

    if ( ! empty( $_POST['user_link'] ) )
        update_post_meta( $order_id, '_user_link', sanitize_text_field( $_POST['user_link'] ) );

}

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

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

The code is tested and working

这篇关于在WooCommerce中添加隐藏的结帐字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆