首页 文章

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

提问于
浏览
1

我希望包含指向通过Woocommerce提交结帐表单的当前用户的 Profiles 的链接 .

也就是说,在隐藏字段中自动放置当前用户的作者链接: 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;
?>

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

谢谢 .

2 回答

  • 4

    使用挂钩在 woocommerce_after_order_notes 动作挂钩中的自定义函数,您还可以直接输出一个隐藏字段,该用户"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文件中,或者放在任何插件文件中 .

    代码经过测试和运行

  • -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/ . 如果这对您有用,请告诉我,如果不是,那么问题是什么 .

相关问题