2017-03-05 69 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 –

相關問題