Как определить поля только для пользовательского типа продукта – Woo Commerce Hook

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

Как я могу ограничить свои пользовательские типы полей английским языком

add_filter( 'product_type_selector', 'english_course_wc_cpt' ); function english_course_wc_cpt( $types ){ $types[ 'wdm_custom_product' ] = __( 'English Courses' ); return $types; } class WC_Product_Wdm extends WC_Product{ public function __construct( $product ) { $this->product_type = 'wdm_custom_product'; parent::__construct( $product ); // add additional functions here } } add_action( 'woocommerce_product_options_general_product_data', 'english_course_custom_fields' ); function english_course_custom_fields() { global $woocommerce, $post; echo '<div class="options_group">'; // Duration: Duration of the course woocommerce_wp_text_input( array( 'id' => 'duration_ec_wc_cpt', 'label' => __( 'Duration', 'woocommerce' ), 'placeholder' => 'Enter the Duration of the Course', 'desc_tip' => 'true', 'description' => __( 'Duration of the Course.', 'woocommerce' ), 'type' => 'text' )); // Fee: Create a number field woocommerce_wp_text_input( array( 'id' => 'fee_ec_wc_cpt', 'label' => __( 'Fee', 'woocommerce' ), 'placeholder' => 'Enter the Fee', 'desc_tip' => 'true', 'description' => __( 'Fee of the course.', 'woocommerce' ), 'type' => 'number' )); // Address: Create a text area field woocommerce_wp_textarea_input( array( 'id' => 'address_ec_wc_cpt', 'label' => __( 'Address', 'woocommerce' ), 'placeholder' => 'Enter the Address', 'desc_tip' => 'true', 'description' => __( 'Address of the course.', 'woocommerce' ), )); echo '</div>'; } /* * SAVING DATA - ENGLISH COURSES (wc_cpt) * postfix/prefix : ec_wc_cpt */ add_action( 'woocommerce_process_product_meta', 'save_ec_wc_cpt' ); function save_ec_wc_cpt( $post_id ){ // Save Duration field $duration_ec_wc_cpt = $_POST['duration_ec_wc_cpt']; if( !empty( $duration_ec_wc_cpt ) ) update_post_meta( $post_id, 'duration_ec_wc_cpt', esc_attr( $duration_ec_wc_cpt) ); // Save Fee field $fee_ec_wc_cpt = $_POST['fee_ec_wc_cpt']; if( !empty( $fee_ec_wc_cpt ) ) update_post_meta( $post_id, 'fee_ec_wc_cpt', esc_attr( $fee_ec_wc_cpt) ); // Save Address field $address_ec_wc_cpt = $_POST['address_ec_wc_cpt']; if( !empty( $fee_ec_wc_cpt ) ) update_post_meta( $post_id, 'address_ec_wc_cpt', esc_attr( $address_ec_wc_cpt) ); } 

Я думаю, что есть два способа сделать это. 1. Либо добавьте настраиваемые поля в свою панель в поле данных продукта. или 2. продолжайте добавлять их в общий захват данных, который вы используете, а затем используйте JS, чтобы скрыть их для других типов продуктов.

Подход 1

 // Creates the admin panel tab add_action( 'woocommerce_product_write_panel_tabs', so_26338834_product_write_panel_tab' ); function product_write_panel_tab() { echo '<li class="wdm_custom_product_tab show_if_wdm_custom_product wdm_custom_product_options"><a href="#wdm_custom_product_data">'.__( 'English Courses' ).'</a></li>'; } // Creates the panel for selecting product options add_action( 'woocommerce_product_write_panels', so_26338834_product_write_panel' ); function product_write_panel() { global $post; ?> <div id="wdm_custom_product_data" class="wdm_custom_product panel panel woocommerce_options_panel wc-metaboxes-wrapper"> <div class="options_group wdm_custom_product"> put your fields here </div> <!-- options group --> </div> <?php } 

Подход 2

Оберните свои входы в div с show_if_{$product_type} . Я думаю, что WooCommerce будет обрабатывать аспекты скрытия / отображения для вас.

 add_action( 'woocommerce_product_options_general_product_data', 'english_course_custom_fields' ); function english_course_custom_fields() { global $woocommerce, $post; echo '<div class="options_group show_if_wdm_custom_product">'; // your inputs echo '</div>'; } 

Изменить: я проверил свой собственный код и обнаружил, что вы должны написать javascript для скрытия / показа себя. Это легко сделать, поскольку WooCommerce запускает настраиваемое событие при изменении ввода типа продукта, поэтому мы можем написать обработчик, который запускает это событие.

 // product type specific options $( 'body' ).on( 'woocommerce-product-type-change', function( event, select_val, select ) { if ( select_val == 'wdm_custom_product' ) { $( '.show_if_wdm_custom_product' ).show(); } else { $( '.show_if_wdm_custom_product' ).hide(); } }); 

Добавьте настраиваемый мета-ящик, а затем добавьте поля в мета-окно

 /** * adding custom box to show custom fields in product create/edit page */ function add_custom_meta_box() { add_meta_box( 'custom_meta_box', // $id 'Deal of Day', // $title 'show_custom_meta_box', // $callback 'product', // $page ( or content type) 'normal', // $context 'high');// $priority } /* * call back functio to render fields in meta box */ function show_custom_meta_box() { global $post; $meta = get_post_meta($post->ID, $field['id'], true); echo '<input type="text" name="name-of-field" id="field-od" value="' . $meta . '" size="30" /> <br /><span class="description">Label</span>'; } add_action('add_meta_boxes', 'add_custom_meta_box' ); 

Вы можете использовать woocommerce_product_options_general_product_data action hook для добавления настраиваемых полей к определенному типу продукта и woocommerce_process_product_meta фильтра woocommerce_process_product_meta для сохранения настраиваемых полей. Подробнее см. Ссылку: http://wisdmlabs.com/blog/create-product-type-custom-settings-woocommerce/ . Это поможет вам.

  1. Создать пользовательскую категорию продукта в Woocommerce; назовите его Custom Product .
  2. Добавьте следующий код в functions.php:

     function isCustomProduct($pid) { $terms = get_the_terms( $id, 'product_cat' ); foreach ($terms as $term) { if ($term->name == 'Custom Product') { return true; } } return false; } 
  3. Добавьте следующую строку в начало english_course_custom_fields() :

     if (!isWyDayProduct($post->ID)) { return; }