Home WordpressWordPress cơ bản Thêm custom fields cho variation product trong woocommerce

Thêm custom fields cho variation product trong woocommerce

by admincp

Bài trước, mình có hướng các bạn sử dụng variation products trong woocommerce trong trường hợp sản phẩm của bạn có nhiều thuộc tính với giá cả khác nhau.
Và có nhiều người hỏi tôi làm sao để có thể thêm trường mới vào variation product. Vì vậy, trong bài hôm nay mình quyết định viết tutorial này sẽ giúp bạn tạo trường mới cho mỗi product variation. Kết quả sau của bài viết bạn sẽ làm được trông giống thế này:
woocommerce-variations-custom-fields[1]

Bên cạnh việc thêm fields cho sản phẩm với loại sản phẩm variation bạn còn có thể thêm field mới cho mỗi variation product. Để làm điều này bạn sẽ cần đến 3 hàm liên kết với 3 hook.
woocommerce_product_after_variable_attributes: Đăng ký fields.
woocommerce_product_after_variable_attributes_js: Hàm thứ hai tạo thêm fields khi nhấn vào nút “add variation” sử dụng javascript.
woocommerce_process_product_meta_variable: Hook cuối cùng, dùng để lưu lại dữ liệu trên fields trong cơ sở dữ liệu.

Trong ví dụ sau đây, mình có sử dụng 6 loại Fields:

  • Text Field
  • Number Field
  • Textarea
  • Dropdown Select
  • Checkbox
  • Hidden field

Cách tạo fields sử dụng woocommerce api mình đã nói trong bài hướng dẫn custom fields cho sản phẩm với woocommerce, bạn có thể xem lại.
Giải thích nguyên lý
Cơ bản không có gì khác nhiều so với cách tạo custom fields cho product nhưng đối với variation dữ liệu được thêm động thông qua sử dụng javascript: Khi bạn nhấn vào “add variation” sẽ tạo ra thẻ div bởi javascript load nội dung fields mới mà bạn có đăng ký với hook nhưng ở đây chúng ta thấy có 2 hook khai báo fields giống nhau. Một hook nạp custom fields đã lưu lại trước đó và hook còn lại dùng cho javascript để load thêm custom fields cho variation mới. Vì vậy tại sao chúng ta cần 2 hook này: woocommerce_product_after_variable_attributeswoocommerce_product_after_variable_attributes_js

Toàn bộ đoạn code cho phần này như sau:

<?php
 
//Display Fields
add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2 );
//JS to add fields for new variations
add_action( 'woocommerce_product_after_variable_attributes_js', 'variable_fields_js' );
//Save variation fields
add_action( 'woocommerce_process_product_meta_variable', 'save_variable_fields', 10, 1 );
 
/**
 * Create new fields for variations
 *
*/
function variable_fields( $loop, $variation_data ) {
?>
	<tr>
		<td>
			<?php
			// Text Field
			woocommerce_wp_text_input( 
				array( 
					'id'          => '_text_field['.$loop.']', 
					'label'       => __( 'My Text Field', 'woocommerce' ), 
					'placeholder' => 'http://',
					'desc_tip'    => 'true',
					'description' => __( 'Enter the custom value here.', 'woocommerce' ),
					'value'       => $variation_data['_text_field'][0]
				)
			);
			?>
		</td>
	</tr>
	<tr>
		<td>
			<?php
			// Number Field
			woocommerce_wp_text_input( 
				array( 
					'id'          => '_number_field['.$loop.']', 
					'label'       => __( 'My Number Field', 'woocommerce' ), 
					'desc_tip'    => 'true',
					'description' => __( 'Enter the custom number here.', 'woocommerce' ),
					'value'       => $variation_data['_number_field'][0],
					'custom_attributes' => array(
									'step' 	=> 'any',
									'min'	=> '0'
								) 
				)
			);
			?>
		</td>
	</tr>
	<tr>
		<td>
			<?php
			// Textarea
			woocommerce_wp_textarea_input( 
				array( 
					'id'          => '_textarea['.$loop.']', 
					'label'       => __( 'My Textarea', 'woocommerce' ), 
					'placeholder' => '', 
					'description' => __( 'Enter the custom value here.', 'woocommerce' ),
					'value'       => $variation_data['_textarea'][0],
				)
			);
			?>
		</td>
	</tr>
	<tr>
		<td>
			<?php
			// Select
			woocommerce_wp_select( 
			array( 
				'id'          => '_select['.$loop.']', 
				'label'       => __( 'My Select Field', 'woocommerce' ), 
				'description' => __( 'Choose a value.', 'woocommerce' ),
				'value'       => $variation_data['_select'][0],
				'options' => array(
					'one'   => __( 'Option 1', 'woocommerce' ),
					'two'   => __( 'Option 2', 'woocommerce' ),
					'three' => __( 'Option 3', 'woocommerce' )
					)
				)
			);
			?>
		</td>
	</tr>
	<tr>
		<td>
			<?php
			// Checkbox
			woocommerce_wp_checkbox( 
			array( 
				'id'            => '_checkbox['.$loop.']', 
				'label'         => __('My Checkbox Field', 'woocommerce' ), 
				'description'   => __( 'Check me!', 'woocommerce' ),
				'value'         => $variation_data['_checkbox'][0], 
				)
			);
			?>
		</td>
	</tr>
	<tr>
		<td>
			<?php
			// Hidden field
			woocommerce_wp_hidden_input(
			array( 
				'id'    => '_hidden_field['.$loop.']', 
				'value' => 'hidden_value'
				)
			);
			?>
		</td>
	</tr>
<?php
}
 
/**
 * Create new fields for new variations
 *
*/
function variable_fields_js() {
?>
	<tr>
		<td>
			<?php
			// Text Field
			woocommerce_wp_text_input( 
				array( 
					'id'          => '_text_field[ + loop + ]', 
					'label'       => __( 'My Text Field', 'woocommerce' ), 
					'placeholder' => 'http://',
					'desc_tip'    => 'true',
					'description' => __( 'Enter the custom value here.', 'woocommerce' ),
					'value'       => $variation_data['_text_field'][0]
				)
			);
			?>
		</td>
	</tr>
	<tr>
		<td>
			<?php
			// Number Field
			woocommerce_wp_text_input( 
				array( 
					'id'                => '_number_field[ + loop + ]', 
					'label'             => __( 'My Number Field', 'woocommerce' ), 
					'desc_tip'          => 'true',
					'description'       => __( 'Enter the custom number here.', 'woocommerce' ),
					'value'             => $variation_data['_number_field'][0],
					'custom_attributes' => array(
									'step' 	=> 'any',
									'min'	=> '0'
								) 
				)
			);
			?>
		</td>
	</tr>
	<tr>
		<td>
			<?php
			// Textarea
			woocommerce_wp_textarea_input( 
				array( 
					'id'          => '_textarea[ + loop + ]', 
					'label'       => __( 'My Textarea', 'woocommerce' ), 
					'placeholder' => '', 
					'description' => __( 'Enter the custom value here.', 'woocommerce' ),
					'value'       => $variation_data['_textarea'][0],
				)
			);
			?>
		</td>
	</tr>
	<tr>
		<td>
			<?php
			// Select
			woocommerce_wp_select( 
			array( 
				'id'          => '_select[ + loop + ]', 
				'label'       => __( 'My Select Field', 'woocommerce' ), 
				'description' => __( 'Choose a value.', 'woocommerce' ),
				'value'       => $variation_data['_select'][0],
				'options' => array(
					'one'   => __( 'Option 1', 'woocommerce' ),
					'two'   => __( 'Option 2', 'woocommerce' ),
					'three' => __( 'Option 3', 'woocommerce' )
					)
				)
			);
			?>
		</td>
	</tr>
	<tr>
		<td>
			<?php
			// Checkbox
			woocommerce_wp_checkbox( 
			array( 
				'id'            => '_checkbox[ + loop + ]', 
				'label'         => __('My Checkbox Field', 'woocommerce' ), 
				'description'   => __( 'Check me!', 'woocommerce' ),
				'value'         => $variation_data['_checkbox'][0], 
				)
			);
			?>
		</td>
	</tr>
	<tr>
		<td>
			<?php
			// Hidden field
			woocommerce_wp_hidden_input(
			array( 
				'id'    => '_hidden_field[ + loop + ]', 
				'value' => 'hidden_value'
				)
			);
			?>
		</td>
	</tr>
<?php
}
 
/**
 * Save new fields for variations
 *
*/
function save_variable_fields( $post_id ) {
	if (isset( $_POST['variable_sku'] ) ) :
 
		$variable_sku          = $_POST['variable_sku'];
		$variable_post_id      = $_POST['variable_post_id'];
		
		// Text Field
		$_text_field = $_POST['_text_field'];
		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
			$variation_id = (int) $variable_post_id[$i];
			if ( isset( $_text_field[$i] ) ) {
				update_post_meta( $variation_id, '_text_field', stripslashes( $_text_field[$i] ) );
			}
		endfor;
		
		// Number Field
		$_number_field = $_POST['_number_field'];
		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
			$variation_id = (int) $variable_post_id[$i];
			if ( isset( $_text_field[$i] ) ) {
				update_post_meta( $variation_id, '_number_field', stripslashes( $_number_field[$i] ) );
			}
		endfor;
		
		// Textarea
		$_textarea = $_POST['_textarea'];
		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
			$variation_id = (int) $variable_post_id[$i];
			if ( isset( $_textarea[$i] ) ) {
				update_post_meta( $variation_id, '_textarea', stripslashes( $_textarea[$i] ) );
			}
		endfor;
		
		// Select
		$_select = $_POST['_select'];
		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
			$variation_id = (int) $variable_post_id[$i];
			if ( isset( $_select[$i] ) ) {
				update_post_meta( $variation_id, '_select', stripslashes( $_select[$i] ) );
			}
		endfor;
		
		// Checkbox
		$_checkbox = $_POST['_checkbox'];
		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
			$variation_id = (int) $variable_post_id[$i];
			if ( isset( $_checkbox[$i] ) ) {
				update_post_meta( $variation_id, '_checkbox', stripslashes( $_checkbox[$i] ) );
			}
		endfor;
		
		// Hidden field
		$_hidden_field = $_POST['_hidden_field'];
		for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
			$variation_id = (int) $variable_post_id[$i];
			if ( isset( $_hidden_field[$i] ) ) {
				update_post_meta( $variation_id, '_hidden_field', stripslashes( $_hidden_field[$i] ) );
			}
		endfor;
		
	endif;
}

Đăng ký fields sử dụng các hàm được tích hợp sẵn trong woocommerce, bạn có thể tìm thấy tại: WooCommerce/Admin/WritePanels/writepanels-init.php

Mình nói thêm phần lưu dữ liệu fields, trong hàm save_variable_fields. Mỗi variation product là một product post meta riêng và mỗi loại field sẽ lưu chung vào mảng được tách riêng ID và value. ID của các variation chứa trong giá trị form $_POST[‘variable_post_id’] và giá trị tương ứng của mỗi loại fields thì chứa trong giá trị mảng tạo bởi form cho từng field name có cấu trúc giống như sau:

<input type="text" name="_number_field[..]"/>

Ví dụ: lấy mảng giá trị của input có name=”_text_field” là $_POST[‘_text_field’] hay $_POST[‘_number_field’],..
Bạn để ý hàm tạo field woocommerce_wp_text_input, id có dạng 'id' => '_number_field['.$loop.']'.

Sử dụng vòng lặp for để lưu giá trị của từng loại fields vào mỗi variation product. Mỗi variation và fields tương ứng sẽ theo thứ tự, nên bạn chỉ việc lặp số lượng các variation product từ 1 đến sizeof($_POST['variable_sku']).

Hiển thị giá trị fields cho variation product

Vì là custom field cho custom post type nên chỉ cần sử dụng hàm get_post_meta(). Chúc bạn thành công.

Để nhận được bài viết mới vui lòng đăng ký kênh kiến thức WordPress từ A-Z ở Form bên dưới. Bạn cũng có thể nhận được sự trợ giúp trên TwitterFacebook

Liên hệ

Công ty chuyên Thiết kế website uy tín nhất Miền Bắc: http://vinastar.net

Hotline tư vấn: 0989 48 3456

Nguồn: Sưu tầm trên internet

You may also like

Leave a Comment