Добавление программно вкладки пользовательских настроек в данные продукта администратора в WooCommerce

Я хочу программно добавить вкладку настроек в «Металлообменные данные» продукта следующим образом:

введите описание изображения здесь

На вкладке «Verzendkosten» был добавлен firebug (что означает «Стоимость доставки») .

Как программно добавить пользовательскую вкладку «Verzendkosten» в настройках страниц редактирования woocommerce?

(и как я мог бы заселить его данными?)

Обновлено в ноябре 2017 года:

  • Исправлены некоторые ошибки, были очищены и добавлены доступные параметры
  • Добавлены «Usage» и «соглашения об именах» для пользовательских полей slugs, в конце.

1) Вы создаете пользовательскую вкладку в настраиваемом типе сообщений Metabox (здесь для «продукта»)
2), то вы можете добавить поля для заполнения этой вкладки различными полями (вы найдете один из каждого типа, так что это очень полный пример).

И, наконец, вы найдете функцию, которая сохраняет данные при отправке.

Здесь вы получите визуально (для 6 различных типов настраиваемых полей):

Пользовательская вкладка продукта метаболизма

Вот связанный код:

// Step 1 - Adding a custom tab to the Products Metabox add_filter( 'woocommerce_product_data_tabs', 'add_shipping_costs_product_data_tab', 99 , 1 ); function add_shipping_costs_product_data_tab( $product_data_tabs ) { $product_data_tabs['shipping-costs'] = array( 'label' => __( 'Shipping costs', 'my_theme_domain' ), // translatable 'target' => 'shipping_costs_product_data', // translatable ); return $product_data_tabs; } // Step 2 - Adding and POPULATING (with data) custom fields in custom tab for Product Metabox add_action( 'woocommerce_product_data_panels', 'add_shipping_costs_product_data_fields' ); function add_shipping_costs_product_data_fields() { global $post; $post_id = $post->ID; echo '<div id="shipping_costs_product_data" class="panel woocommerce_options_panel">'; ## THE 6 DIFFERENT FIELD TYPES // Text imput field // Text imput field woocommerce_wp_text_input( array( 'id' => '_imput_text', // 'name' => '_imput_text', // (optional) for different ID attribute than name attribute // 'class' => 'some-class', // (optional) // 'wrapper_class' => 'show_if_simple', // (optional) example here for simple products type only 'placeholder' => __( 'Enter some data', 'theme_domain' ), // (optional) 'label' => __( 'Imput text Label', 'theme_domain' ), // (optional) 'description' => __( 'Imput text Description', 'theme_domain' ), // (optional) 'desc_tip' => true, // (optional) To show the description as a tip // 'data_type' => '', // (optional formatting options) can be 'price', 'decimal', 'stock' or 'url' // 'type' => '', // (optional additional custom attribute) // 'value' => $value, // (optional) for a static value (can be conditionally set for $value variable) ) ); // Textarea imput field woocommerce_wp_textarea_input( array( 'id' => '_input_textarea', // 'name' => 'input_textarea', // (optional) for different ID attribute than name attribute 'class' => 'widefat', // (optional) // 'style' => '' // (optional) // 'wrapper_class' => 'show_if_simple', // (optional) example here for simple products type only 'placeholder' => __( 'Enter some data', 'theme_domain' ), // (optional) 'label' => __( 'Imput textarea Label', 'theme_domain' ), 'description' => __( 'Imput textarea Description', 'theme_domain' ), 'desc_tip' => true, // (optional) To show the description as a tip // 'rows' => 2, // (optional) defining number of rows // 'cols' => 20, // (optional) defining number of columns // 'value' => $value, // (optional) for a static value (can be conditionally set for $value variable) ) ); // Checkbox field woocommerce_wp_checkbox( array( 'id' => '_input_checkbox', // 'name' => 'input_checkbox', // (optional) for different ID attribute than name attribute // 'class' => 'some-class', // (optional) // 'wrapper_class' => 'show_if_simple', // (optional) example here for simple products type only 'label' => __( 'Imput checkbox Label', 'theme_domain' ), 'description' => __( 'Imput checkbox Description', 'theme_domain' ), 'desc_tip' => true, // (optional) To show the description as a tip // 'cbvalue' => 'yes', // to make it selected by default // 'value' => $value, // (optional) for a static value (can be conditionally set for $value variable) ) ); // Radio Buttons field woocommerce_wp_radio( array( 'id' => '_imput_radio', // 'name' => 'input_radio', // (optional) for different ID attribute than name attribute // 'class' => 'some-class', // (optional) // 'wrapper_class' => 'show_if_simple', // (optional) example here for simple products type only 'label' => __(' ', 'my_theme_domain'), 'description' => __( 'Imput Radio Description', 'my_theme_domain' ), 'desc_tip' => true 'options' => array( 'option_value_1' => __('Displayed option 1'), 'option_value_2' => __('Displayed option 2'), 'option_value_3' => __('Displayed option 3'), ), // 'value' => $value, // (optional) for a static value (can be conditionally set for $value variable) ) ); // Select field woocommerce_wp_select( array( 'id' => '_select_field', // 'name' => '_select_field', // (optional) for different ID attribute than name attribute // 'wrapper_class' => 'show_if_simple', // (optional) example here for simple products type only 'label' => __(' ', 'my_theme_domain'), 'description' => __( 'Imput Radio Description', 'my_theme_domain' ), 'desc_tip' => true 'options' => array( '' => __('Chose an option'), // Default empty value 'option_value_1' => __('Displayed option 1'), 'option_value_2' => __('Displayed option 2'), 'option_value_3' => __('Displayed option 3') ), // 'value' => $value, // (optional) for a static value (can be conditionally set for $value variable) ) ); // Hidden imput field woocommerce_wp_hidden_input( array( 'id' => '_hidden_input', // 'name' => '_hidden_input', // (optional) for different ID attribute than name attribute 'class' => 'some_class', // 'value' => $value, // (optional) for a static value (can be conditionally set for $value variable) ) ); echo '</div>'; } // Step 3 - Saving custom fields data of custom products tab metabox add_action( 'woocommerce_process_product_meta', 'shipping_costs_process_product_meta_fields_save' ); function shipping_costs_process_product_meta_fields_save( $post_id ){ // save the text field data if( isset( $_POST['_imput_text'] ) ) update_post_meta( $post_id, '_imput_text', esc_attr( $_POST['_imput_text'] ) ) ); // save the textarea field data if( isset( $_POST['_imput_textarea'] ) ) update_post_meta( $post_id, '_imput_textarea', esc_attr( $_POST['_imput_textarea'] ) ) ); // save the checkbox field data if( isset( $_POST['_imput_checkbox'] ) ) update_post_meta( $post_id, '_imput_checkbox', esc_attr( $_POST['_imput_checkbox'] ) ) ); // save the radio button field data if( isset( $_POST['_input_radio'] ) ) update_post_meta( $post_id, '_input_radio', esc_attr( $_POST['_input_radio'] ) ) ); // save the selector field data if( isset( $_POST['_select_field'] ) ) update_post_meta( $post_id, '_select_field', esc_attr( $_POST['_select_field'] ) ) ); // save the hidden imput data if( isset( $_POST['_hidden_input'] ) ) update_post_meta( $post_id, '_hidden_input', esc_attr( $_POST['_hidden_input'] ) ); } 

Естественно, это продолжается в файле functions.php вашей активной дочерней темы (или темы) или в любом файле плагина.

На шагах 2 и 3 вы должны использовать один и тот же пользовательский идентификатор поля (имена slug) .

Этот код проверен и полностью работоспособен

Вы можете добавить пользовательские параметры с ЛЮБЫМИ ДАННЫМИ, используя пользовательский код, пользовательские переменные или любые функции на шаге 2 .


Применение

Чтобы получить или получить данные, вы будете использовать get_post_meta() для определенного идентификатора сообщения :

 $custom_field_data = get_post_meta( $post_id, '_custom_field_slug', true ); 

Где:

  • $post_id – это текущий идентификатор сообщения (из продукта, заказа, купона … post-types).
  • custom_field_slug – это идентификатор (slug) вашего настраиваемого поля.
  • true или false : следует ли возвращать одно значение (строка данных или массивы)

Это один и тот же процесс каждого вида полей


Совет. Пользовательские имена полей (пользовательский идентификатор поля)

Если вы не используете символ подчеркивания ( _slug_name ) в начале имен slug ваших настраиваемых полей , они появятся и будут доступны для авторизованных пользователей в настраиваемых полях Metabox после отправки данных (кнопка «Обновить») .

См. Этот снимок экрана (здесь мы получаем поле input_text пользовательского поля input_text ) :

Пользовательские поля metabox


Рекомендации:

  • Добавить вкладку, которая видна только в стороне администратора продукта в woocommerce
  • Пакет WooCommerce> Администратор> Функции
  • WooCommerce Multi Select для отдельного поля продукта
  • Ссылка на WP Code – get_post_meta ()
  • Ссылка на WP Code – update_post_meta ()