管理woocommerce中的自定义结帐字段

时间:2016-10-24 14:03:24

标签: woocommerce customization checkout

您好我对woocommerce中的自定义结帐字段有疑问。 我在结帐表单中创建了一个自定义字段,一切都运行良好。该字段包含客户卡号。我还设法在wp-usermeta中保存了字段值(一旦第一次输入),因此它不会仅与订单一起出现,而是与客户详细信息一起保存。

现在我想做以下事情。一旦返回商店的注册客户进入结账表单,新字段(如果不是empyt)将自动显示,而不是每次都要求客户插入他们的卡号。

我添加到我的子主题fucntions.php中的原始函数用于在结帐页面中显示自定义字段:

  /**
 * Add the field to the checkout
 */
add_action ('woocommerce_after_order_notes', 'checkout_w55_card_number' );

  function checkout_w55_card_number( $checkout ) {

      echo '<div id="checkout_w55_card_number"><h2>' . __('N. tessera W55') . '</h2>';

      woocommerce_form_field( 'w55_card_number', array(
          'type'          => 'text',
          'class'         => array('w55-card-number-class form-row-wide'),
          'label'         => __('Inserisci n. tessera W55'),
          'placeholder'   => __('Inserisci numero'),
          ), $checkout->get_value( 'w55_card_number' ));
      echo '</div>';
}

我因此试图以这种方式重新安排它,但它不起作用

add_action ('woocommerce_after_order_notes', 'checkout_w55_card_number' );

function checkout_w55_card_number( $checkout ) {
//extracts the value of the w55_card_number field
$w55_card = get_user_meta($user_id, 'w55_card_number', true);
//condition is the w55_card_number field is empty or not 
if ( !empty($w55_card) ) : echo $w55_card;      else :

          echo '<div id="checkout_w55_card_number"><h2>' . __('N. tessera W55') . '</h2>';

          woocommerce_form_field( 'w55_card_number', array(
              'type'          => 'text',
              'class'         => array('w55-card-number-class form-row-wide'),
              'label'         => __('Inserisci n. tessera W55'),
              'placeholder'   => __('Inserisci numero'),
              ), $checkout->get_value( 'w55_card_number' ));
          echo '</div>';
         endif;
   }

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您的user_id变量未定义。您需要执行以下操作:

add_action ('woocommerce_after_order_notes', 'checkout_w55_card_number' );

function checkout_w55_card_number( $checkout ) {
    $user_id = get_current_user_id();
    $w55_card = '';
    if ($user_id) {
         //extracts the value of the w55_card_number field
         $w55_card = get_user_meta($user_id, 'w55_card_number', true);
    }
    //condition is the w55_card_number field is empty or not 
    if ( !empty($w55_card) ) : echo $w55_card;      
    else :
      echo '<div id="checkout_w55_card_number"><h2>' . __('N. tessera W55') . '</h2>';
      woocommerce_form_field( 'w55_card_number', array(
          'type'          => 'text',
          'class'         => array('w55-card-number-class form-row-wide'),
          'label'         => __('Inserisci n. tessera W55'),
          'placeholder'   => __('Inserisci numero'),
          ), $checkout->get_value( 'w55_card_number' ));
      echo '</div>';
     endif;

}