我想包含一个指向通过 WooCommerce 提交结帐表单的当前用户的个人资料的链接。
也就是说,自动将当前用户的作者链接放置在隐藏字段中,如下所示:example.com/author/username
我想通过在结帐表单中添加隐藏字段来实现此目的。因此,为了获得链接,我会写这样的内容:
<?php
$currentUser = get_current_user_id();
$user = get_user_by( 'id', $currentUser );
$userUrl = get_bloginfo( 'home' ) . '/author/' . $user->user_login;
echo $userUrl;
?>
我的问题是如何在结账表单中创建这种类型的隐藏字段?
挂钩自定义函数woocommerce_after_order_notes
动作钩子,您还可以直接输出一个隐藏字段,以该用户“作者链接”作为隐藏值,当客户下订单时,该隐藏字段将与所有结帐字段同时提交。
这是该代码:
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 文件中或任何插件文件中。
代码已经过测试并且可以工作
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)