Jump to content

Guardar dados de campos adicionais


Anfanger

Recommended Posts

Boas,
Estou a tentar adicionar quatro campos na página de checkout e guardar os inputs do user para depois apresentar nos detalhes da encomenda (página thankyou e backoffice).
Estou a fazê-lo da seguinte forma:

 

//Display custom fields
add_filter( 'woocommerce_checkout_before_customer_details', 'message_zone' );
function message_zone( $msg ) {


  $domain = 'woocommerce';
    $checkout = WC()->checkout;

    $shipping_method ='flat_rate:1'; // Set the desired shipping method to hide the checkout field(s).
    global $woocommerce;
    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0];


    if ($chosen_shipping == $shipping_method) 
    {
        echo '<p>O destino de entrega da encomenda encontra-se fora do raio de entregas por nós previsto. Os custos associados ao transporte terão de ser alvo de análise. Pedimos que preencha o seguinte formulário para que possamos fazer uma avaliação e assim que oportuno entraremos em contacto para finalizar-mos a sua encomenda.</p><p></p>';

        echo '<div id="my_custom_checkout_field">';

        echo '<h3>' . __('Detalhes de encomenda:') . '</h3>';

        woocommerce_form_field( '_shipping_address', array(
        'type'          => 'text',
        'label'         => __('Morada de entrega', $domain ),
        'placeholder'   => __('Introduza a morada de entrega', $domain ),
        'class'         => array('my-field-class form-row-wide'),
        'required'      => true, // or false
       ), $checkout->get_value( '_shipping_address' ) );

        woocommerce_form_field( '_postal_code', array(
        'type'          => 'text',
        'label'         => __('Código Postal', $domain ),
        'placeholder'   => __('Introduza o código postal', $domain ),
        'class'         => array('my-field-class form-row-wide'),
        'required'      => true, // or false
       ), $checkout->get_value( '_postal_code' ) );

         echo '<h5>' . __('Contacto em obra:') . '</h5>';

         woocommerce_form_field( '_name', array(
        'type'          => 'text',
        'label'         => __('Nome da pessoa em obra', $domain ),
        'placeholder'   => __('Introduza o nome da pessoa em obra que irá receber a encomenda', $domain ),
        'class'         => array('my-field-class form-row-wide'),
        'required'      => true, // or false
       ), $checkout->get_value( '_name' ) );

           woocommerce_form_field( '_tlm', array(
        'type'          => 'text',
        'label'         => __('Telemóvel', $domain ),
        'placeholder'   => __('Introduza o contacto telefónico da pessoa em obra que irá receber a encomenda', $domain ),
        'class'         => array('my-field-class form-row-wide'),
        'required'      => true, // or false
       ), $checkout->get_value( '_tlm' ) );

       echo '</div>';
    }
    else
      echo '';

    echo $msg;
}


// Custom checkout fields validation
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
    // Check if set, if its not set add an error.
    if ( ! $_POST['_shipping_address'] )
        wc_add_notice( __( 'Prencha a morada de entrega' ), 'error' );
    if ( ! $_POST['_postal_code'] )
        wc_add_notice( __( 'Preencha o código postal' ), 'error' );     
    if ( ! $_POST['_name'] )
        wc_add_notice( __( 'Preencha o nome da pessoa em obra' ), 'error' );
    if ( ! $_POST['_tlm'] )
        wc_add_notice( __( 'Prencha o contacto telefónico' ), 'error' );              
}


//save custom fields
function save_extra_checkout_fields( $order_id, $posted )
{
    // don't forget appropriate sanitization if you are using a different field type
    if( isset( $posted['_shipping_address'] ) ) 
    {
        update_post_meta( $order_id, '_shipping_address', sanitize_text_field( $posted['_shipping_address'] ) );
    }
    if( isset( $posted['_postal_code'] ) ) 
    {
        update_post_meta( $order_id, '_postal_code', sanitize_text_field( $posted['_postal_code'] ) );
    }
    if( isset( $posted['_name'] ) ) 
    {
        update_post_meta( $order_id, '_name', sanitize_text_field( $posted['_name'] ) );
    }
    if( isset( $posted['_tlm'] ) ) 
    {
        update_post_meta( $order_id, '_tlm', sanitize_text_field( $posted['_tlm'] ) );
    }
}
add_action( 'woocommerce_checkout_update_order_meta', 'save_extra_checkout_fields', 10, 2 );


//Display custom fields in thankyou page
function display_order_data( $order_id ){  ?>
    <h2><?php _e( 'Detalhes da encomenda:' ); ?></h2>
    <table class="shop_table shop_table_responsive additional_info">
        <tbody>
            <tr>
                <th><?php _e( 'Morada de entrega:' ); ?></th>
                <td><?php echo get_post_meta( $order_id, '_shipping_address', true ); ?></td>
            </tr>
            <tr>
                <th><?php _e( 'Código Postal:' ); ?></th>
                <td><?php echo get_post_meta( $order_id, '_postal_code', true ); ?></td>
            </tr>
            <tr>
                <th><?php _e( 'Nome da pessoa em obra:' ); ?></th>
                <td><?php echo get_post_meta( $order_id, '_name', true ); ?></td>
            </tr>
            <tr>
                <th><?php _e( 'Contacto telefónico:' ); ?></th>
                <td><?php echo get_post_meta( $order_id, '_tlm', true ); ?></td>
            </tr>
        </tbody>
    </table>
<?php }
add_action( 'woocommerce_thankyou', 'display_order_data', 20 );
add_action( 'woocommerce_view_order', 'display_order_data', 20 );


//Display custom fields in order page (backoffice)
function display_order_data_in_admin( $order ){  ?>
    <div class="order_data_column">
        <h4><?php _e( 'Detalhes da encomenda:', 'woocommerce' ); ?><a href="#" class="edit_address"><?php _e( 'Editar', 'woocommerce' ); ?></a></h4>
        <div class="address">
        <?php
            echo '<p><strong>' . __( 'Morada de entrega' ) . ':</strong>' . get_post_meta( $order->id, '_shipping_address', true ) . '</p>';
            echo '<p><strong>' . __( 'Código Postal' ) . ':</strong>' . get_post_meta( $order->id, '_postal_code', true ) . '</p>';
            echo '<p><strong>' . __( 'Nome da pessoa em obra' ) . ':</strong>' . get_post_meta( $order->id, '_name', true ) . '</p>';
            echo '<p><strong>' . __( 'Contacto telefónico' ) . ':</strong>' . get_post_meta( $order->id, '_tlm', true ) . '</p>';
            ?>
        </div>
        <div class="edit_address">
            <?php woocommerce_wp_text_input( array( 'id' => '_shipping_address', 'label' => __( 'Morada de entrega:' ), 'wrapper_class' => '_billing_company_field' ) ); ?>
            <?php woocommerce_wp_text_input( array( 'id' => '_postal_code', 'label' => __( 'Código Postal:' ), 'wrapper_class' => '_billing_company_field' ) ); ?>
            <?php woocommerce_wp_text_input( array( 'id' => '_name', 'label' => __( 'Nome da pessoa em obra:' ), 'wrapper_class' => '_billing_company_field' ) ); ?>
            <?php woocommerce_wp_text_input( array( 'id' => '_tlm', 'label' => __( 'Contacto telefónico:' ), 'wrapper_class' => '_billing_company_field' ) ); ?>
        </div>
    </div>
<?php }
add_action( 'woocommerce_admin_order_data_after_order_details', 'display_order_data_in_admin' );


function save_extra_details( $post_id, $post )
{
    update_post_meta( $post_id, '_shipping_address', wc_clean( $_POST[ '_shipping_address' ] ) );
    update_post_meta( $post_id, '_postal_code', wc_clean( $_POST[ '_postal_code' ] ) );
    update_post_meta( $post_id, '_name', wc_clean( $_POST[ '_name' ] ) );
    update_post_meta( $post_id, '_tlm', wc_clean( $_POST[ '_tlm' ] ) );
}
add_action( 'woocommerce_process_shop_order_meta', 'save_extra_details', 45, 2 );

Os campos são criados, apresentados na página thankyou e order details (backoffice), mas por alguma razão não me apresenta os inputs introduzidos pelo user.
Detalhes de encomenda (thankyou page)
Detalhes de encomenda (backoffice/admin page)

Alguém me consegue dar uma ajuda ?

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.