2017-03-05 65 views
1

我想包含一个链接,指向通过Woocommerce提交结账表单的当前用户的个人资料。在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; 
?> 

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

感谢。

回答

3

随着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文件儿童主题(或主题)或任何插件文件。

该代码已测试并正在工作

+0

嗨,谢谢你。你有任何想法如何在订单页面和订单电子邮件中显示此作者链接? –

+0

我想如何在任何人需要的时候在订单邮件中放置作者链接:'add_filter('woocommerce_email_order_meta_fields','custom_woocommerce_email_order_meta_fields',10,3); 功能custom_woocommerce_email_order_meta_fields($字段,$ sent_to_admin,$顺序){ $领域[ '_ USER_LINK'] =阵列( '标签'=> __( '用户链接'), '值'=> get_post_meta($顺序 - > id,'_user_link',true), ); return $ fields; }' –

-1

添加到您的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/这里http://woocommerce.wp-a2z.org/oik_api/woocommerce_form_field/。请让我知道,如果这对你有用,如果不是什么问题。

+0

其他一些问题出现:)试图先解决它们。会让你知道 –

+0

''type'=>'hidden''不被'woocommerce_form_field'支持。检查:http://hookr.io/functions/woocommerce_form_field/获取函数定义。您需要添加像这里显示的自定义代码:https://stackoverflow.com/a/25622464/332188 –

相关问题