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

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

bởi Thắng ơi!
110 lượt xem

Tổng hợp các đoạn code về woocommerce mà bạn có thể dùng khi chỉnh sửa và thay đổi cho phù hợp trong Woocommerce

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(); ?>

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

Copy đoạn mã vào functions.php

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();
}

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

Copy đoạn mã vào functions.php

/**
 * 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;
}

Tiếp tục copy đoạn mã vào header.php

<?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

Copy đoạn mã vào functions.php

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

Chèn đoạn mã trên vào nơi bạn muốn hiển thị 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.'">';
}
?>

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.

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>

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 )); 
}

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

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/logo.png);
   margin: 0 auto 1rem;
   width: 30%;
   height:120px;
   background-size: 100% 100%;
   ;';
   echo '
</style>
';
}

18. Thay đổi SKU 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

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.

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

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

Chèn đoan mã dưới vào functions.php

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 );

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

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. 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' );
  
   }
}

25. 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' );
  
   }

26. 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;
} );

Bài viết liên quan

Bình luận