在 WooCommerce 中添加隐藏的结帐字段?

Adding a hidden checkout field in WooCommerce?

我想将 link 添加到通过 WooCommerce 提交结帐表单的当前用户的个人资料中。

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

我想通过在结帐表单中添加隐藏字段来实现此目的。所以为了得到 link 我会写这样的东西:

<?php

$currentUser = get_current_user_id();

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

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

echo $userUrl;
?>

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

将此添加到您的 functions.php 文件(或插件文件等)

add_action( 'woocommerce_after_order_notes', 'hidden_author_field' );

function hidden_author_field( $checkout ) {

$currentUser = get_current_user_id();
$user = get_user_by( 'id', $currentUser );
$userUrl = get_bloginfo('home').'/author/'.$user->user_login;

    woocommerce_form_field( 'hidden_author', array(
        'type'          => 'hidden',
        'class'         => array('hidden form-row-wide'),
        ), $userUrl);

}

此代码未经测试,更多信息请阅读此处 https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/ and here http://woocommerce.wp-a2z.org/oik_api/woocommerce_form_field/。请让我知道这是否对您有用,如果不是,问题是什么。

通过在woocommerce_after_order_notes action hook中挂接自定义函数,也可以直接输出一个以该用户"author link"作为隐藏值的隐藏字段,将在客户下订单时与所有结帐字段同时提交。

代码如下:

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

然后你需要在订单中保存这个隐藏字段,这样:

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

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