Tổng hợp các đoạn code về woocommerce

Nối tiếp bài Những đoạn code hay dùng trong lập trình theme wordpress thì bây giờ mình tiếp tục viết về những tips mà mình tổng hợp được trong quá trình làm việc. Nó rất hữu ích cho các bạn đấy nhé :)). Let’s go ……………………

1. Hiễn thị sản phẩm mới nhất trong woocommerce

<?php $args = array( 'post_type' => 'product','posts_per_page' =>10,); ?>
    <?php $getposts = new WP_query( $args);?>
    <?php global $wp_query; $wp_query->in_the_loop = true; ?>
    <?php while ($getposts->have_posts()) : $getposts->the_post(); ?>
    <?php global $product; ?>
	<div>
		<a href="<?php the_permalink(); ?>">
			<?php echo get_the_post_thumbnail( get_the_id(), 'full', array( 'class' =>'thumnail') ); ?>
		</a>
		<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
		<?php echo $product->get_price_html(); ?>
	</div>
<?php endwhile;  wp_reset_postdata(); ?>
  • posts_per_page = 10: Hiễn thị 10 sản phẩm

2. Hiễn thị sản phẩm theo danh mục trong woocommerce

<?php $args = array( 'post_type' => 'product','posts_per_page' =>5, 'product_cat' => 'clothes'); ?>
    <?php $getposts = new WP_query( $args);?>
    <?php global $wp_query; $wp_query->in_the_loop = true; ?>
    <?php while ($getposts->have_posts()) : $getposts->the_post(); ?>
    <?php global $product; ?>
	<div class="product-detail">
		<a href="<?php the_permalink(); ?>">
			<?php echo get_the_post_thumbnail( get_the_id(), 'full', array( 'class' =>'thumnail') ); ?>
		</a>
		<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
		<?php echo $product->get_price_html(); ?>
	</div>
<?php endwhile;  wp_reset_postdata(); ?>
  • post_type => product : Hiễn thị theo product
  • posts_per_page =>5: Hiễn thị 5 sản phẩm
  • product_cat => clothes: Hiễn thị theo danh mục có slug là clothes, bạn có thể hiễn thị theo Id: ‘cat’ => 2, trong đó 2 là id danh mục cần lấy.

3. Hiễn thị sản phẩm nổi bật trong woocommerce

<?php $args = array( 'post_type' => 'product','posts_per_page' =>10, 'meta_key' => '_featured','meta_value' => 'yes',); ?>
<?php $getposts = new WP_query( $args);?>
<?php global $wp_query; $wp_query->in_the_loop = true; ?>
<?php while ($getposts->have_posts()) : $getposts->the_post(); ?>
<?php global $product; ?>
	<div class="product-detail">
		<a href="<?php the_permalink(); ?>">
			<?php echo get_the_post_thumbnail( get_the_id(), 'full', array( 'class' =>'thumnail') ); ?>
		</a>
		<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
		<?php echo $product->get_price_html(); ?>
	</div>
<?php endwhile;  wp_reset_postdata(); ?>
  • meta_key => _featured: Chỉ hiễn thị key là sản phẩm nổi bật, trong database có sản phẩm giảm giá các kiểu nửa,…

4. Hiễn thị danh mục sản phẩm trong woocommerce

<ul>
<?php $args = array( 
    'hide_empty' => 0,
    'taxonomy' => 'product_cat',
    'orderby' => id,
    'parent' => 0
    ); 
    $cates = get_categories( $args ); 
    foreach ( $cates as $cate ) {  ?>
		<li>
			<a href="<?php echo get_term_link($cate->slug, 'product_cat'); ?>"><?php echo $cate->name ?></a>
		</li>
<?php } ?>
</ul>

5. Tạo nút quick view ( mua hàng nhanh ) trong woocommerce

Đầu tiên, bạn copy đoạn code này vào file functions.php nhé.

add_filter ('woocommerce_add_to_cart_redirect', 'redirect_to_checkout');
function redirect_to_checkout($checkout_url) {
    global $woocommerce;
    if($_GET['quick_buy']) {
        $checkout_url = $woocommerce->cart->get_checkout_url();
    }
    return $checkout_url;
}

Đoạn này $checkout_url = $woocommerce->cart->get_checkout_url() thì trõ tới trang checkout , còn nếu bạn muốn trõ tới trang sản phẩm thôi thì sửa lại đoạn code như này nhé $checkout_url = $woocommerce->cart->get_cart_url();

Tiếp theo, bạn chèn đoạn code này vào nơi bạn muốn hiễn thị nút quick view.

<a href="<?php echo get_home_url(); ?>/?quick_buy=1&add-to-cart=<?php echo get_the_ID(); ?>" class="qn_btn"></a>

Thường thì mình hay thêm nút quick view ở trang chi tiết sản phẩm, bên cạnh nút mua hàng. Bạn hãy thử và cho mình biết thành quả nhé.

6. Đổi chữ sale thành phần trăm ( % ) giảm giá trong woocommerce

add_filter('woocommerce_sale_flash','itseovn_woocommerce_sale_flash', 10, 3);
function itseovn_woocommerce_sale_flash($text, $post, $product){
    ob_start();
    $sale_price = get_post_meta( $product->get_id(), '_price', true);
    $regular_price = get_post_meta( $product->get_id(), '_regular_price', true);
    if (empty($regular_price) && $product->is_type( 'variable' )){
        $available_variations = $product->get_available_variations();
        $variation_id = $available_variations[0]['variation_id'];
        $variation = new WC_Product_Variation( $variation_id );
        $regular_price = $variation ->regular_price;
        $sale_price = $variation ->sale_price;
    }
    $sale = ceil(( ($regular_price - $sale_price) / $regular_price ) * 100);
    if ( !empty( $regular_price ) && !empty( $sale_price ) && $regular_price > $sale_price ) :
        $R = floor((255*$sale)/100);
        $G = floor((255*(100-$sale))/100);
        $bg_style = 'background:none;background-color: rgb(' . $R . ',' . $G . ',0);';
        echo apply_filters( 'itseovn_woocommerce_sale_flash', '<span class="onsale" style="'. $bg_style .'">-' . $sale . '%</span>', $post, $product );
    endif;
    return ob_get_clean();
}

Đoạn code này bạn chèn vào file functions.php nhé. Truy cập vào wp-content / theme / [ten-theme] / functions.php

7. Code lấy số lượng sản phẩm nhảy vào giỏ hàng

Code lấy số lượng. Nhớ chèn đoạn này vài file functions.php nhé.

/**
 * Ensure cart contents update when products are added to the cart via AJAX
 */
add_filter('woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cartplus_fragment');
function woocommerce_header_add_to_cartplus_fragment( $fragments ) {
    global $woocommerce;
    ob_start();
    ?>
	<span class="c-item cart-contents-count">
		<?php echo $woocommerce->cart->cart_contents_count; ?>
	</span>
    <?php
    $fragments['span.c-item'] = ob_get_clean();//a.cartplus-contents,a.cart-button
	ob_end_clean();
    return $fragments;
}

Xong bạn tiếp tục chèn đoạn code này vào file header.php , nơi có giỏ hàng. Chỉ cần copy rồi dán vào thì sẽ hoạt động tốt nha.

<?php $count= WC()->cart->cart_contents_count; // Get thoomg tin sp ?>
<a title="Xem chi tiết" href="<?php echo get_home_url(); ?>/gio-hang">
   <div class="count">
      <?php
         if ($count > 0) {
         ?>
      <span class="c-item cart-contents-count">
      <?php echo esc_html( $count ); ?>
      </span>
      <?php
         }
         ?>
   </div>
   <i class="fa fa-shopping-bag"></i><span>Giỏ hàng</span>
</a>

Lấy tổng giá:

<?php echo $woocommerce->cart->get_cart_total();

8. Xóa url product trong woocommerce

Việc tối ưu đường dẫn để chuẩn seo hơn, tối ưu url. Các bạn copy và dán vào file functions.php nha

add_filter('term_link', 'tvc_term_parents', 1000, 3);
function tvc_term_parents($url, $term, $taxonomy) {
    if($taxonomy == 'product_cat'){
        $term_nicename = $term->slug;
        $url = trailingslashit(get_option( 'home' )) . user_trailingslashit( $term_nicename, 'category' );
    }
    return $url;
}
 
// Add our custom product cat rewrite rules
function tvc_product_cat_parents_rewrite_rules($flash = false) {
    $terms = get_terms( array(
        'taxonomy' => 'product_cat',
        'post_type' => 'product',
        'hide_empty' => false,
    ));
    if($terms && !is_wp_error($terms)){
        foreach ($terms as $term){
            $term_slug = $term->slug;
            add_rewrite_rule($term_slug.'/?$', 'index.php?product_cat='.$term_slug,'top');
            add_rewrite_rule($term_slug.'/page/([0-9]{1,})/?$', 'index.php?product_cat='.$term_slug.'&paged=$matches[1]','top');
            add_rewrite_rule($term_slug.'/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$', 'index.php?product_cat='.$term_slug.'&feed=$matches[1]','top');
        }
    }
    if ($flash == true)
        flush_rewrite_rules(false);
}
add_action('init', 'tvc_product_cat_parents_rewrite_rules');
 
/*Sửa lỗi khi tạo mới taxomony bị 404*/
add_action( 'create_term', 'tvc_new_product_cat_edit_success', 10);
add_action( 'edit_terms', 'tvc_new_product_cat_edit_success', 10);
add_action( 'delete_term', 'tvc_new_product_cat_edit_success', 10);
function tvc_new_product_cat_edit_success( ) {
    tvc_product_cat_parents_rewrite_rules(true);
}

9. Hiễn thị tất cả gallery ảnh của sản phẩm

global $product;
$attachment_ids = $product->get_gallery_image_ids();
foreach( $attachment_ids as $attachment_id ) {
$image_link = wp_get_attachment_url( $attachment_id );
 echo '<img src="'.$image_link.'">';
}
?>

Đoạn code này bạn chèn vào nơi mà bạn mún hiễn thị nha.

10. Đoạn code để theme nhận template chính của woocommerce

Nếu như bạn không thêm đoạn này củng được, nhưng giao diện như category, single nó sẽ k kế thừa được giao diện mặt định của woocommerce.

function my_custom_wc_theme_support() {
  add_theme_support( 'woocommerce' );
  add_theme_support( 'wc-product-gallery-lightbox' );
  add_theme_support( 'wc-product-gallery-slider' );
}
add_action( 'after_setup_theme', 'my_custom_wc_theme_support' );

11. Tùy biến size image

add_image_size('product_image_small', 400, 400, false);
add_image_size('product_image_large', 700, 700, false);

===== echo $bien[‘sizes’]['product_image_small'’]

12. Code lấy slide sữ dụng slide của bootstrap

<!-- Get post News Query --> 
<?php $getposts = new WP_query(); 
$getposts->query('post_status=publish&showposts=5&post_type=sliders'); 
$i = 1; ?> 
<?php global $wp_query; $wp_query->in_the_loop = true; ?> 
<?php while ($getposts->have_posts()) : $getposts->the_post(); ?> 
<?php $featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full'); ?> 
<?php if($i == 1){ ?> 
   <div class="carousel-item active"> 
     <?php echo get_the_post_thumbnail(get_the_ID(), 'full', array('class' => 'd-block w-100' )); ?> 
   </div>
<?php } 
else { 
 ?> 
   <div class="carousel-item"> <?php echo get_the_post_thumbnail(get_the_ID(), 'full', array('class' => 'd-block w-100' )); ?> </div>
 <?php } 
?> 
<?php $i++; ?> 
<?php endwhile; wp_reset_postdata(); ?> 
<!-- Get post News Query -->

showposts=5: Lấy số lượng slide mún hiễn thị.

post_type=slide: Lấy theo post type có tên là slide. Nó giống như kiểu post type Post trong này sẽ quản lý các bài viết của bạn. Củng giống như post type Slide mình tạo ra riêng 1 post type để quản lý mỗi slide không thôi. Việc khởi tạo 1 post type cực kì đơn giản, xem qua bài viết của mình Tạo custom post type trong wordpress để dể dàng tạo post type cho riêng mình nha.

13. Code lấy danh mục sản phẩm theo ID

<div class="heading">
   <?php $cat = get_term_by('id', 17, 'product_cat') ?> 
   <a href="<?php echo get_term_link($cat->slug, 'product_cat');?>"><?php echo $cat->name; ?></a> 
   <ul class="parent-item">
      <?php $args = array( 'type' => 'product', 'child_of' => 0, 'hide_empty'=> 0, 'number' => 5, 'taxonomy' => 'product_cat', 'parent' => $cat->term_id ); 
         $categories = get_categories( $args ); 
         foreach ( $categories as $category ) 
         { ?> 
      <li> <a href="<?php echo get_term_link($category->slug, 'product_cat');?>"><i class="fa fa-caret-right"></i><?php echo $category->name; ?></a> </li>
      <?php } ?> 
   </ul>
</div>

Ở ví dụ trên mình mún lấy danh mục sản phẩm có id là 17.

14. Chuyển giá O đ  thành giá Liên hệ

function tvc_wc_custom_get_price_html( $price, $product ) {
    if ( $product->get_price() == 0 ) {
        if ( $product->is_on_sale() && $product->get_regular_price() ) {
            $regular_price = wc_get_price_to_display( $product, array( 'qty' => 1, 'price' => $product->get_regular_price() ) );
 
            $price = wc_format_price_range( $regular_price, __( 'Free!', 'woocommerce' ) );
        } else {
            $price = '<span class="amount">' . __( 'Liên hệ', 'woocommerce' ) . '</span>';
        }
    }
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'tvc_wc_custom_get_price_html', 10, 2 );

15. Tạo Theme Option bằng plugin Advanced Custom Fields

// Create Theme Option 
if( function_exists('acf_add_options_page') ) { 
acf_add_options_page(array( 
'page_title' => 'Theme options', 
'menu_title' => 'Theme options', 
'menu_slug' => 'theme-settings', 
'capability' => 'edit_posts', 
'redirect' => false )); 
}

Việc này bạn cần phải cài đặt trước plugin Advanced Custom Fields Pro nha mọi người. Link tải plugin tại đây.

16. Thay đổi text Quick View trong theme Flatsome

function my_custom_translations( $strings ) {
$text = array(
  'Quick View' => 'Xem nhanh'
);
$strings = str_ireplace( array_keys( $text ), $text, $strings );
 return $strings;
}
add_filter( 'gettext', 'my_custom_translations', 20 );

17. Thêm logo login trong wordpress

Việc thay đổi logo login trong wordpress để làm tăng thêm bản quyền cho web của mình, nhìn chuyên nghiệp hơn.

add_action( 'login_enqueue_scripts', 'giuseart_login_enqueue_scripts' );
function giuseart_login_enqueue_scripts(){
echo '
<style type="text/css" media="screen">';
   echo '#login h1 a
   {
   background-image:url(' .get_home_url(). '/wp-content/uploads/2021/02/logo_03.png);
   margin: 0 auto 1rem;
   width: 28%;
   height:100px;
   background-size: 100% 100%;
   ;';
   echo '
</style>
';
}

Bạn thay đổi logo ở đường dẫn trong cặp thẻ <style></style>. Mình có thêm 1 số style cho đẹp logo hơn, bạn có thể tham khảo và thay đổi tùy theo ý của bạn nha.

18. Thay đổi SKU thành Mã sản phẩm

Mã sản phẩm là tính năng không thể thiếu với web bán hàng, giúp khách hàng và người bán tìm kiếm dễ hơn. Mặc định Woo để là SKU dịch thành Mã sản phẩm:

function translate_woocommerce($translation, $text, $domain) {
if ($domain == 'woocommerce') {
switch ($text) {
case 'SKU':
 $translation = 'Mã sản phẩm:';
break;
case 'SKU:':
 $translation = 'Mã sản phẩm:';
 break;
}
}
 return $translation;
}
add_filter('gettext', 'translate_woocommerce', 10, 3);

19. Hiễn thị SKU ra ngoài danh mục sản phẩm

add_action( 'woocommerce_before_shop_loop_item_title', 'shop_sku' );
function shop_sku(){
global $product;
 echo ' <div class="sku">Mã SP: ' . $product->sku . '</div> ';
}

Hiển thị Mã sản phẩm SKU ra ngoài page Danh mục sản phẩm, ngay bên dưới ảnh thumb sản phẩm giúp khách hàng thấy mã ngay khi view.

20. Dịch breadcrum trong giỏ hàng

Đây là vấn đề mình hay gặp khi các bạn vừa mới vào lập trình wordpress. Nó là đường dẫn Breadcrumb của trang Giỏ hàng. Nhiều bạn sẽ dùng plugin translate loco để dịch. Nhưng các bạn biết đấy việc cài đặt thêm plugin mà nhu cầu không dùng tới bao nhiêu thì chỉ làm thêm nặng web. Nhắc tới plugin thì mình có chia sẽ 1 plugin mình vừa mới viết, chức năng và công dụng như thế nào thì bạn có thể đọc nó ở đây nhé.

SHOPPING CART -> CHECKOUT DETAILS -> ORDER COMPLETE

// Translate Shopping Cart Breadcrumb
add_filter( 'gettext', function ( $strings ) {

$text = array(
'SHOPPING CART' => 'Giỏ hàng',
'CHECKOUT DETAILS' => 'Thanh toán',
'ORDER COMPLETE' => 'Hoàn tất',
);
$strings = str_ireplace( array_keys( $text ), $text, $strings );
return $strings;
}, 20 );

Các bạn chèn đoạn code này vào file functions.php nhé.

21. Đổi chữ đ thành VND trong woocommerce

Mặt định trong woo thì giá của Viet Nam mình là đồng ( đ ), nhưng nhiều khách hàng thì mún chuyển nó thành VND. Thì code ở dưới sẽ giải quyết vấn đề nha.  Chèn nó vào file functions.php nhé

/**
 Change a currency symbol đ to VND
 */
 add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2); 
 function change_existing_currency_symbol( $currency_symbol, $currency ) {
 switch( $currency ) {
   case 'VND': $currency_symbol = 'VND'; break;
 }
 return $currency_symbol;
 }

22. Đổi chữ đặt hàng thành Đặt tour

Nhiều website về du lịch nhưng vẫn sử dụng woocommerce để dể tùy biến các sản phẩm tour của họ, thì việc thay đổi nút đặt hàng thành đặt tour thì rất cần thiết nhé.

Change Place Order button text on checkout page in woocommerce
*/
 
add_filter('woocommerce_order_button_text','custom_order_button_text',1);
function custom_order_button_text($order_button_text) {
	$order_button_text = 'ĐẶT TOUR';
	return $order_button_text;
}

23. Đưa mô tả chi tiết sản phẩm lên trên

Mô tả sản phẩm thì nó thường đặt ở dưới mô tả ngắn, nhiều khách mún đặt mô tả chi tiết này lên trên thì phải làm sao. Bạn chèn đoạn code này vào file functions.php nhé.

add_action ( 'woocommerce_before_variations_form', 
'show_attributes', 25 );function show_attributes() {
  global $product;
  wc_display_product_attributes ($product);
}

add_filter( 'woocommerce_product_tabs', 
'woo_remove_product_tabs', 98 );
function woo_remove_product_tabs( $tabs ) {
    unset( $tabs['additional_information'] );  	//emove the additional information tab
    return $tabs;
}

24. Các shortcode cho woocommerce

1. Hiễn thị sản phẩm mới nhất

[recent_products per_page="12" columns="4"]

2. Hiễn thị sản phẩm nổi bật

[featured_products per_page="12" columns="4"]

3. Hiễn thị sản phẩm theo ID

[product id="88"]

4. Hiễn thị sản phẩm giảm giá

[sale_products per_page="12"]

5. Hiễn thị sản phẩm bán chạy

[best_selling_products per_page="12"]

6. Hiễn thị sản phẩm theo danh mục

[product_category category="Ten danh muc"]

25. Thay đổi text ” Read More (Đọc tiếp) ” trong woocommerce

add_filter( 'woocommerce_product_add_to_cart_text', function( $text ) {
    if ( 'Read more' == $text ) {
        $text = __( 'More Info', 'woocommerce' );
    }

    return $text;
} );

26. Kiểm tra xem ID sản phẩm có được chứa trong giỏ hàng hay không

add_action( 'woocommerce_before_cart', 'bbloomer_find_product_in_cart' );
    
function bbloomer_find_product_in_cart() {
  
   $product_id = 282;
  
   $product_cart_id = WC()->cart->generate_cart_id( $product_id );
   $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
  
   if ( $in_cart ) {
  
      $notice = 'Product ID ' . $product_id . ' is in the Cart!';
      wc_print_notice( $notice, 'notice' );
  
   }

27. Kiểm tra xem ID Sản phẩm có trong Giỏ hàng Qua Vòng lặp

add_action( 'woocommerce_before_cart', 'bbloomer_find_product_in_cart_alt' );
    
function bbloomer_find_product_in_cart_alt() {
  
   $product_id = 282;
   $in_cart = false;
  
   foreach( WC()->cart->get_cart() as $cart_item ) {
      $product_in_cart = $cart_item['product_id'];
      if ( $product_in_cart === $product_id ) $in_cart = true;
   }
  
   if ( $in_cart ) {
  
      $notice = 'Product ID ' . $product_id . ' is in the Cart!';
      wc_print_notice( $notice, 'notice' );
  
   }
  
}

Tổng kết

Trên đây là tổng hợp những đoạn code hay dùng trong lập trình woocommerce mà mình đã tổng hợp được, mình vẫn đang tích lũy trong quá trình làm việc và sẽ cập nhật tiếp trên bài viết này nha.

Mọi người mún xem nhiều bài viết cập nhật mới nhất thì ghé qua chuyên mục này nhé Mẹo – thủ thuật