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 » Sắp xếp sản phẩm Woocommerce theo ý muốn

Sắp xếp sản phẩm Woocommerce theo ý muốn

Thứ Ba, 19/02/2019 by Hoàng Quách

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

Bạn muốn xắp xếp sản phẩm trong Woocommerce trong quản trị WordPress theo ý muốn. Cách đơn giản nhất là sử dụng plugin Post Types Order. Sau khi kích hoạt plugin, bạn truy cập menu Products > Order & bắt đầu xắp xếp bằng cách kéo thả theo ý của bạn, sau đó lưu lại cài đặt.

Giải pháp thứ 2, bạn có thể chủ động cấu hình vị trí của từng bài viết, cách này sẽ yêu cầu bạn thêm code vào tệp giao diện. Trước khi thực hiện chúng tôi khuyến khích bạn thực hiện sao lưu WordPress an toàn.

Để thêm cột thứ tự vào bảng quản lý sản phẩm của woocommerce, bạn sử dụng filter filter:manage_{tên post type}_posts_columns.

add_filter( 'manage_product_posts_columns', 'product_columns_2' );
function product_columns_2( $existing_columns ) {
		if ( empty( $existing_columns ) && ! is_array( $existing_columns ) ) {
			$existing_columns = array();
		}

		unset( $existing_columns['title'], $existing_columns['comments'], $existing_columns['date'], $existing_columns['product_tag'] );
		
		$columns          = array();
		$columns['ordering']         = 'Thứ tự<a href="#" class="saveorderingdddd"><span class="dashicons dashicons-filter"></span></a>';

		return array_merge( $columns, $existing_columns );

}

Để lấy giá trị của custom field của ordering cho từng dòng, bạn sử dụng hook action có tên:manage_{tên post type}_posts_custom_column.

//show ordering
add_action( 'manage_product_posts_custom_column',  'render_product_columns_2' , 3);
function render_product_columns_2( $column ) {
	global $post, $the_product;

	if ( empty( $the_product ) || $the_product->id != $post->ID ) {
		$the_product = wc_get_product( $post );
	}

	switch ( $column ) {
		case 'ordering' :
		?>
			<input type="text" style="width:50px; text-align:center;" value="<?php echo  get_post_meta($post->ID,'_product_ordering',true); ?>" name="ordering[]"  />
			<?php
			break;
		
		default :
			break;
	}
}

Tiếp theo, mình sẽ thêm custom field vào tab general woocommerce.

// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
  
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields() {
  
  global $woocommerce, $post;
   
  echo '<div class="options_group">';
  // Text Field
woocommerce_wp_text_input( 
    array( 
        'id'          => '_product_ordering', 
        'label'       => __( 'Thứ tự', 'woocommerce' ), 
        'placeholder' => '',
        'desc_tip'    => 'true',
        'description' => __( '', 'woocommerce' ) ,
		//'value' => 0
    )
);

  echo '</div>';
}
function woo_add_custom_general_fields_save( $post_id ){
     
      
    // Text Field
    $woocommerce_text_field = $_POST['_product_ordering'];
    if( !empty( $woocommerce_text_field ) )
        update_post_meta( $post_id, '_product_ordering', esc_attr( $woocommerce_text_field ) );
	
         
}

Thêm Ajax xử lý lưu giá trị ordering. Bạn đăng ký file js với wordpress.

function my_enqueue($hook) {

    wp_enqueue_script( 'smn-ordering', get_template_directory_uri() . '/js/ordering.js' );
	wp_localize_script( 'smn-ordering', 'ordering_ob', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );

Tạo tệp ordering.js với nội dung sau:

jQuery(function($){
	//alert('sdfsd;');
	$(".saveorderingdddd").click(function(){
		var post=document.getElementsByName('post[]');
		var post_ids ='';

		for(key=0; key < post.length; key++)  {
			if(key == 0){
				post_ids =post[key].value;
			}else{
				post_ids = post_ids+","+post[key].value;
			}
		
			//your code goes here
		}
		var order=document.getElementsByName('ordering[]');
		var orderings ='';

		for(key=0; key < order.length; key++)  {
			if(key == 0){
				orderings =order[key].value;
			}else{
				orderings = orderings +","+order[key].value;
			}
		
			//your code goes here
		}
		$.ajax({
            type: 'POST',
            url: ordering_ob.ajaxurl,
            data:{action: 'ordering',post_ids:post_ids,orderings:orderings},
            success: function(data){
				console.log(data);
                if(data == "data"){
					 location.reload();
				}
            }
        });
		
		return false;
	});
});

Thêm hàm sử lý ajax trong functions.php

add_action('wp_ajax_ordering','ordering_function');
add_action('wp_ajax_nopriv_ordering','ordering_function');
function ordering_function(){
	$post_ids = explode(",",$_POST['post_ids']);
	$orderings = explode(",",$_POST['orderings']);
	for($i=0;$i<count($post_ids);$i++):
		update_post_meta($post_ids[$i], "_product_ordering", $orderings[$i]);
	endfor;
	echo "data";
	die();
}

Bước quan trọng, giúp bạn sắp xếp lại theo custom field trong quản trị WordPress.

//resort list product
add_filter( 'parse_query', 'fb_custom_post_sort' );
function fb_custom_post_sort($query) {

    if ( ! is_admin() )
        return $query;

    global $current_screen;
    if ( isset( $current_screen ) && 'product' === $current_screen->post_type ) {
        $query->query_vars['orderby']  = 'meta_value_num';
        $query->query_vars['meta_key'] = '_product_ordering';
        $query->query_vars['order']    = 'ASC';
    }
}

Tương tự, chúng ta cần xắp xếp sản phẩm trên website, chúng ta sử dụng wp_query như sau cho mỗi truy vấn.

 $args = array(
	'post_type' => 'product',
	'posts_per_page' => 12,
	'meta_key'   => '_product_ordering',
	'orderby'    => 'meta_value_num',
	'order'      => 'ASC',
	'post_status' => 'publish'
);

$wp_query = new WP_Query( $args );

Bạn cũng muốn xem hướng dẫn xắp xếp thứ tự hiển thị category và taxonomies trong wordpress.

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

Comments

  1. Hoàng says

    Thứ Bảy, 04/05/2019 at 4:45 chiều

    cho mình hỏi là copy đoạn code này vào file nào vậy

    • Hoàng Quách says

      Thứ Bảy, 04/05/2019 at 9:40 chiều

      chào bạn, bạn hỏi đoạn code nào? trong bài viết mình có ghi tên file, bạn hãy đọc kĩ nhé

  2. Danh Hoàng says

    Thứ Bảy, 03/08/2019 at 3:31 chiều

    Các dòng code đầu tiên thì thêm vào file nào vậy bạn?

    • Hoàng Quách says

      Chủ Nhật, 04/08/2019 at 8:01 sáng

      Tất cả các đoạn code bạn thêm vào file functions.php của thư mục giao diện bạn đang dùng nhé.

  3. Danh says

    Thứ Bảy, 03/08/2019 at 3:42 chiều

    Cho mình hỏi các dòng code từ đầu tới “thêm custom field vào tab general woocommerce” thì thêm ở file nào vậy bạn? Mình cám ơn

  4. Danh says

    Chủ Nhật, 04/08/2019 at 9:13 sáng

    Đoạn code cuối cùng mình thêm vào thì nó mất trắng tất cả các trang luôn, không biết thêm đoạn đó ở đâu vậy bạn?
    $args = array(
    ‘post_type’ => ‘product’,
    ‘posts_per_page’ => 12,
    ‘meta_key’ => ‘_product_ordering’,
    ‘orderby’ => ‘meta_value_num’,
    ‘order’ => ‘ASC’,
    ‘post_status’ => ‘publish’
    );

    $wp_query = new WP_Query( $args );

    • Hoàng Quách says

      Chủ Nhật, 04/08/2019 at 9:38 sáng

      bạn kiểm tra lại cú pháp PHP nhé, hoặc nếu không sửa được thì chat trên hoangweb.com để bên mình check cho bạn.

  5. huy says

    Thứ Sáu, 10/04/2020 at 10:01 chiều

    Tất cả các đoạn code bạn thêm vào file functions.php của thư mục giao diện bạn đang dùng nhé. mình thêm hết code vô mà sao nó báo lỗi vậy làm sao đây?

    • Hoàng Quách says

      Thứ Bảy, 11/04/2020 at 1:58 chiều

      Để biết chi tiết bạn cần bật logs lỗi trong WordPress.

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.