Добавить настраиваемые поля в существующую форму на Dokan (wordpress / woocoomerce)

Я пытаюсь добавить настраиваемые поля в Dokan (плагин woocommerce - http://demo.wedevs.com/dokan/) настройки продавца для редактирования значений с адреса пользователя в woocommerce. У Докана есть форма на интерфейсе, где продавцы могут редактировать настройки своего магазина. Я изменил свои темы functions.php с помощью этого кода:

 <?php

function endereco() {
 $user_id = get_current_user_id();
	    ?>               <div class="gregcustom dokan-form-group">
                <label class="dokan-w3 dokan-control-label" for="setting_address"><?php _e( 'Cidade', 'dokan' ); ?></label>
                <div class="dokan-w5">
	<input type="text" class="dokan-form-control input-md valid" name="billing_first_name" id="reg_billing_first_name" value="<?php echo esc_attr_e( $_POST['billing_city'] ); ?>" />
   
 				</div>  	</div>   
                
                 <div class="gregcustom dokan-form-group">
                    <label class="dokan-w3 dokan-control-label" for="setting_address"><?php _e( 'Estado', 'dokan' ); ?></label>
                <div class="dokan-w5">
	<input type="text" class="dokan-form-control input-md valid" name="billing_first_name" id="reg_billing_first_name" value="<?php esc_attr_e( $_POST['billing_state'] ); ?>" />
				</div>
                </div>
                
                 <div class="gregcustom dokan-form-group"> 
                    <label class="dokan-w3 dokan-control-label" for="setting_address"><?php _e( 'CEP', 'dokan' ); ?></label>
                <div class="dokan-w5">
	<input type="text" class="dokan-form-control input-md valid" name="billing_first_name" id="reg_billing_first_name" value="<?php esc_attr_e( $_POST['billing_postcode'] ); ?>" />
				</div>   	</div>    
                 <div class="gregcustom dokan-form-group">
                    <label class="dokan-w3 dokan-control-label" for="setting_address"><?php _e( 'Endereço', 'dokan' ); ?></label>
                <div class="dokan-w5">
	<input type="text" class="dokan-form-control input-md valid" name="billing_first_name" id="reg_billing_first_name" value="<?php esc_attr_e( $_POST['billing_address_1'] ); ?>" />
				</div>
                </div>
				
				<?php
}
add_filter( 'dokan_settings_after_banner', 'endereco');

/**
 * Save the extra fields.
 *
 * @param  int  $customer_id Current customer ID.
 *
 * @return void
 */
function save_extra_endereco_fields( $customer_id ) {
	if ( isset( $_POST['billing_city'] ) ) {
		// WordPress default first name field.
		update_user_meta( $customer_id, 'billing_city', sanitize_text_field( $_POST['billing_city'] ) );
	}

	if ( isset( $_POST['billing_postcode'] ) ) {
		// WordPress default last name field.
		update_user_meta( $customer_id, 'billing_postcode', sanitize_text_field( $_POST['billing_postcode'] ) );

	}

	if ( isset( $_POST['billing_state'] ) ) {
		// WooCommerce billing phone
		update_user_meta( $customer_id, 'billing_state', sanitize_text_field( $_POST['billing_address_1'] ) );
	}

	if ( isset( $_POST['billing_address_1'] ) ) {
		// WooCommerce billing phone
		update_user_meta( $customer_id, 'billing_address_1', sanitize_text_field( $_POST['billing_address_1'] ) );
	}
}

add_action( 'dokan_store_profile_saved', 'save_extra_endereco_fields' );

Форма отображается нормально, но не обновляет метаданные пользователя. Еще одна вещь, которую я не смог сделать без ошибок, - это показать текущее значение в поле ввода формы.

я думаю, что это довольно просто для хорошего программиста. Может кто-нибудь мне помочь? Большое спасибо.


person Greg    schedule 18.11.2014    source источник


Ответы (3)


Попробуйте вместо этого этот код:

function endereco( $current_user, $profile_info ) {
        $billing_city = isset( $profile_info['billing_city'] ) ? $profile_info['billing_city'] : '';
        $billing_postcode = isset( $profile_info['billing_postcode'] ) ? $profile_info['billing_postcode'] : '';
        $billing_state = isset( $profile_info['billing_state'] ) ? $profile_info['billing_state'] : '';
        $billing_address_1 = isset( $profile_info['billing_address_1'] ) ? $profile_info['billing_address_1'] : '';
        ?>      
        <div class="gregcustom dokan-form-group">
            <label class="dokan-w3 dokan-control-label" for="setting_address"><?php _e( 'Cidade', 'dokan' ); ?></label>
            <div class="dokan-w5">
                        <input type="text" class="dokan-form-control input-md valid" name="billing_city" id="reg_billing_city" value="<?php echo $billing_city; ?>" />
                </div>
        </div>  

        <div class="gregcustom dokan-form-group">
                <label class="dokan-w3 dokan-control-label" for="setting_address"><?php _e( 'Estado', 'dokan' ); ?></label>
                <div class="dokan-w5">
                        <input type="text" class="dokan-form-control input-md valid" name="billing_postcode" id="reg_billing_postcode" value="<?php echo $billing_postcode; ?>" />
                </div>
        </div>

        <div class="gregcustom dokan-form-group">
                <label class="dokan-w3 dokan-control-label" for="setting_address"><?php _e( 'CEP', 'dokan' ); ?></label>
                <div class="dokan-w5">
                        <input type="text" class="dokan-form-control input-md valid" name="billing_state" id="reg_billing_state" value="<?php echo $billing_postcode; ?>" />
                </div>
        </div>    
        <div class="gregcustom dokan-form-group">
                <label class="dokan-w3 dokan-control-label" for="setting_address"><?php _e( 'Endereço', 'dokan' ); ?></label>
                <div class="dokan-w5">
                        <input type="text" class="dokan-form-control input-md valid" name="billing_address_1" id="reg_billing_address_1" value="<?php echo $billing_address_1; ?>" />
                </div>
        </div>

        <?php
}
add_filter( 'dokan_settings_after_banner', 'endereco', 10, 2);

/**
 * Save the extra fields.
 *
 * @param  int  $customer_id Current customer ID.
 *
 * @return void
 */
function save_extra_endereco_fields( $store_id, $dokan_settings ) {
        if ( isset( $_POST['billing_city'] ) ) {
                $dokan_settings['billing_city'] = $_POST['billing_city'];
        }

        if ( isset( $_POST['billing_postcode'] ) ) {
                $dokan_settings['billing_postcode'] = $_POST['billing_postcode'];
        }

        if ( isset( $_POST['billing_state'] ) ) {
                $dokan_settings['billing_state'] = $_POST['billing_state'];
        }

        if ( isset( $_POST['billing_address_1'] ) ) {
                $dokan_settings['billing_address_1'] = $_POST['billing_address_1'];
        }
        update_user_meta( $store_id, 'dokan_profile_settings', $dokan_settings );
}

add_action( 'dokan_store_profile_saved', 'save_extra_endereco_fields', 10, 2 );

Надеюсь, это решит ваши проблемы.

person Mohaiminul Islam    schedule 20.11.2014
comment
Большой! Спасибо. Но это не обновляет адрес пользователя woocommerce, я добавил, update_user_meta ($ stoer_id, 'billing_city', sanitize_text_field ($ _POST ['billing_city'])); к каждому сообщению о функции сохранения, и я работал! Большое спасибо, чувак. - person Greg; 20.11.2014

Если вы хотите добавить настраиваемое поле, например seller_url, в настройку Dokan, см. Код ниже.

/*Extra field on the seller settings and show the value on the store banner -Dokan*/


// Add extra field in seller settings


add_filter( 'dokan_settings_after_banner', 'extra_fields', 10, 2);


function extra_fields( $current_user, $profile_info ){
$seller_url= isset( $profile_info['seller_url'] ) ? $profile_info['seller_url'] : '';
?>
 <div class="gregcustom dokan-form-group">
    <label class="dokan-w3 dokan-control-label" for="setting_address">
        <?php _e( 'Website', 'dokan' ); ?>
    </label>
    <div class="dokan-w5">
        <input type="text" class="dokan-form-control input-md valid" name="seller_url" id="reg_seller_url" value="<?php echo $seller_url; ?>" />
    </div>
</div>
<?php
}

Следующим шагом является сохранение настроек, используя приведенный ниже код. Это не перезапишет существующую настройку.

    //save the field value


add_action( 'dokan_store_profile_saved', 'save_extra_fields', 15 );
function save_extra_fields( $store_id ) {
    if ( isset( $_POST['seller_url'] ) ) {
        $dokan_settings['seller_url'] = $_POST['seller_url'];
    }


    $existing_dokan_settings = get_user_meta( $store_id, 'dokan_profile_settings', true );
    $prev_dokan_settings     = ! empty( $existing_dokan_settings ) ? $existing_dokan_settings : array();
    $dokan_settings = array_merge( $prev_dokan_settings,$dokan_settings);
    update_user_meta( $store_id, 'dokan_profile_settings', $dokan_settings );
}
person Jirawat Akkanit    schedule 10.05.2017

У меня была такая же проблема, и я нашел этот ответ. Я использовал метод Сергея Белозёрова, который мне очень помог, но он частично сработал, по крайней мере, в моем случае.

Со мной произошло то, что сохранялись только новые настройки, а все старые настройки (другими словами, исходные, а не настроенные) удалялись при каждом обновлении настроек.

Это произошло потому, что в dokan ловушка do_action «dokan_store_profile_saved» принимает только 1 аргумент, store_id. Не было передано dokan_settings, поэтому новая функция

update_user_meta( $store_id, 'dokan_profile_settings', $dokan_settings );

обновлял только последний созданный массив $ dokan_settings, перезаписывая все остальные аргументы $ dokan_settings пустыми значениями.

Поэтому мне пришлось полагаться только на переменную $ store_id и функцию get_user_meta (), и мне это понравилось (учтите, что мне нужно еще одно дополнительное поле, отличное от тех, которые вам нужны):

function save_extra_concept_field( $store_id ) {
        if ( isset( $_POST['vendor_concept'] ) ) {
                $dokan_settings['vendor_concept'] = $_POST['vendor_concept'];
                //update_user_meta( $store_id, 'vendor_concept', sanitize_text_field( $_POST['vendor_concept'] ) ); 
        }
        $prev_dokan_settings = get_user_meta( $store_id, 'dokan_profile_settings', true );
        $dokan_settings = array_merge($prev_dokan_settings,$dokan_settings);
        update_user_meta( $store_id, 'dokan_profile_settings', $dokan_settings );
}

Надеюсь, это поможет и кому-то другому.

person Max D.    schedule 16.02.2016