Hoàng Web

Thiết Kế Website WordPress

  • Kho giao diện
  • Dịch Vụ
    • Thiết kế web giá rẻ
    • Thiết kế website WordPress
    • Hosting Miễn Phí 100GB
    • Tích hợp thanh toán MoMo, ViettelPay, Vietcombank, MB..
    • Tối ưu Google PageSpeed
    • Sửa lỗi nâng cấp website
    • Viết plugin WordPress
    • Code Tool theo yêu cầu
  • Bảng giá
  • Quy trình làm việc
  • Giới thiệu
  • Liên Lạc
Trang chủ » Wordpress » Wordpress plugins » Thêm custom fields cho variation product trong woocommerce

Thêm custom fields cho variation product trong woocommerce

Thứ Tư, 17/09/2014 by Hoàng Quách

  • shares
  • Facebook
  • Facebook Messenger
  • Gmail
  • Viber
  • Skype

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_attributes và woocommerce_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

  • woocommerce_wp_text_input()
  • woocommerce_wp_textarea_input()
  • woocommerce_wp_select()
  • woocommerce_wp_checkbox()
  • woocommerce_wp_hidden_input()

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.

Hãy cho mình biết suy nghĩ của bạn trong phần bình luận bên dưới bài viết này. Hãy theo dõi kênh chia sẻ kiến thức WordPress của Hoangweb trên Twitter và Facebook

  • shares
  • Facebook
  • Facebook Messenger
  • Gmail
  • Viber
  • Skype

Chuyên mục: Wordpress, Wordpress plugins Tìm kiếm: web bán hàng, Woocommerce, wordpress plugins

Comments

  1. Tạ Thủy says

    Thứ Năm, 18/09/2014 at 8:53 chiều

    Khi tạo variations cho sản phẩm trong wooccomerce của WordPress e muốn nó hiển thị giá lớn nhất của 1 sản phẩm ở trong Shop thì phải làm thế nào.

    Ví dụ như ở trong hình e tạo 2 variations 5L có giá 1048000, 1L:240000. E muốn nó hiển thị trong Shop là giá của 5L chứ không phải 1 lít thì phải chỉnh sửa ở chỗ nào. Anh biết giúp e với

    Link ảnh : https://lh5.googleusercontent.com/axQfhtSISH_zmY_y3O5Jk_0AaoU20P9K5qfwAyOEPbg=w852-h575-no
    https://lh6.googleusercontent.com/-KeUYeNqlI_k/VBrjSTpCrrI/AAAAAAAABSw/MsMLZpGTaAg/w280-h346-no/images2.pngủy

    • Hoàng Quách says

      Thứ Bảy, 20/09/2014 at 10:42 sáng

      Bạn sử dụng code này nhé:

      add_filter( 'woocommerce_get_price_html', 'wpa83367_price_html',10,2);
      function wpa83367_price_html( $price, $product ){
      	if($product->product_type=='variable'){
      		return $product->max_variation_price;
      	}
      	return $price;
      }
      

      Chi tiết: http://www.hoangweb.com/wordpress-site/tuy-bien-gia-cho-san-pham-trong-woocommerce

  2. Luong Phu says

    Thứ Ba, 24/09/2019 at 11:05 chiều

    Cho mình hỏi, mình có 3 size S, M, L và muốn hiển thị cho tất cả sản phẩm để kh chọn khi mua hàng, thì sẽ làm ntn ạ?
    Những sp cập nhật về sau cũng sẽ tự động hiển thị 3 size này mà ko cần phải làm sản phẩm biến thể cho từng sp.
    Xin cảm ơn!

    • Hoàng Quách says

      Thứ Tư, 25/09/2019 at 3:15 chiều

      sự tiện lợi của woocommerce variations giúp kh chọn 2 hay nhiều biến thể của các sản phẩm và thay đổi được giá. nếu bạn không muốn dùng tính năng này thì có thể tự code tùy chỉnh thêm option từ attributes.

Tôi giúp gì cho bạn?

HOÀNG WEB

Địa chỉ: Tây Sơn, Phường Quang Trung, Quận Đống Đa, Hà Nội

Hotline: 0987 342 124 – 0868 292 303 (8h:00 – 21h:00)

Email: [email protected]

Website: www.hoangweb.com

KẾT NỐI VỚI TÔI

  • Facebook
  • GitHub
  • YouTube

SẢN PHẨM

  • Plugin Thanh Toán Quét Mã QR Code Tự Động
  • WP2Speed – Tối ưu Google Speed
  • 23WebHost – Hosting Miễn Phí 100GB

LIÊN KẾT

  • Có nên thuê thiết kế website giá rẻ?
  • Hướng dẫn thanh toán
  • Chính sách hoàn tiền
  • Trung tâm hỗ trợ

Copyright © 2023 | All rights reserved | HOANG WEB
Mọi hình thức sao chép nội dung trên website này mà chưa được sự đồng ý đều là trái phép.