Những đoạn code hay dùng trong lập trình theme woocommecre wordpress

Hôm trước mình đã có share một số đoạn code dùng trong lập trình theme wordpress và đã được các bạn ủng hộ nhiệt tình. Vì thế hôm nay mình quyết định tiếp tục chia sẽ một số đoạn code hay dùng trong lập trình theme woocommecre. Woocommecre là plugin rất thông dụng trong wordpress, nắm bắt được nó là bạn có thể giải quyết được bài toán web bán hàng trong wordpress.

Tương tự như bài trước các bạn chỉ cần cop về đặt ở vị trí phù hợp là oke.

1. Code hiển thị 10 sản phẩm mới nhất.

<?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; ?>
 <li>
  <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(); ?>
 </li>
<?php endwhile;  wp_reset_postdata(); ?>

Trong đó:

<?php global $product; ?>
// Là biến toàn cục get sản phẩm
<?php echo $product->get_price_html(); ?>
// Lấy giá sản phẩm
<?php echo get_the_post_thumbnail( $post_id, 'full', array( 'class' =>'thumnail') ); ?>
// Lấy thumbnail sản phẩm

2. Code hiển thị 10 sản phẩm theo danh mục sản phẩm

<?php $args = array( 'post_type' => 'product','posts_per_page' =>10, 'product_cat' => 'dien-thoai'); ?>
    <?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; ?>
 <li>
  <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(); ?>
 </li>
<?php endwhile;  wp_reset_postdata(); ?>

Trong đó :

‘product_cat’ => ‘dien-thoai’ : Là slug của danh mục cần get.

3. Code hiển thị 10 sản phẩm nổi bật.

<?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; ?>
 <li>
  <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(); ?>
 </li>
<?php endwhile;  wp_reset_postdata(); ?>

4. Code hiển thị 10 sản phẩm giảm giá.

<?php $args = array( 
  'post_type' => 'product',
  'posts_per_page' => 10, 
  'meta_query'     => array(
            'relation' => 'OR',
            array(
                'key'           => '_sale_price',
                'value'         => 0,
                'compare'       => '>',
                'type'          => 'numeric'
            )
        )
    ); ?>
<?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; ?>
 <li>
  <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(); ?>
 </li>
<?php endwhile; wp_reset_postdata();?>

5. Code hiển thị 10 sản phẩm xếp hạng đánh giá từ cao đến thấp

<?php $args = array(
  'posts_per_page' => 10,
  'post_status'    => 'publish',
  'post_type'      => 'product',
  'meta_key'       => '_wc_average_rating',
  'orderby'        => 'meta_value_num',
  'order'          => 'DESC',
 );?>
<?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; ?>
 <li>
  <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(); ?>
 </li>
<?php endwhile; wp_reset_postdata();?>

6. Code hiển thị danh mục sản phẩm.

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

7. Code thêm sản phẩm vào giỏ hàng và hiện thị số lượng sản phầm đang có trong giỏ hàng.

// Code thêm sản phẩm vào giỏ hàng
<form action-xhr="#" method="post">
 <input type="hidden" name="add-to-cart" value="<?php the_id(); ?>">
 <button class="addc"><i class="fa fa-cart-plus" aria-hidden="true"></i> Thêm vào giỏ</button>
</form>
// Code hiển thị số lượng sản phẩm đang có trong giỏ hàng
<p>Giỏ hàng: <?php echo sprintf (_n( '%d Sản phẩm', '%d Sản phẩm', WC()->cart->cart_contents_count ), WC()->cart->cart_contents_count ); ?> - <?php echo WC()->cart->get_cart_total(); ?></p>

Lưu ý: <?php the_id(); ?> là ID của sản phẩm cần thêm vào giỏ.

8. Code tạo form tìm kiếm sản phẩm

Tìm kiếm sản phẩm với từ khóa.

<form action="<?php bloginfo('url'); ?>/" method="GET" role="form">
 <input type="hidden" name="post_type" value="product">
 <input type="text" class="form-control" id="name" name="s" placeholder="Nhập tên sản phẩm...">
 <button type="submit" class="btn btn-primary">Tìm kiếm</button>
</form>

Tìm kiếm sản phẩn với từ khóa và danh mục sản phẩm.

<form action="<?php bloginfo('url'); ?>/" method="GET" role="form">
 <input type="hidden" name="post_type" value="product">
 <input type="text" class="form-control" id="name" name="s" placeholder="Nhập tên sản phẩm...">
 <select name="product_cat" id="inputProduct_cat" class="form-control" required="required">
  <option value="">Chọn danh mục</option>
  <?php $args = array( 
      'hide_empty' => 0,
      'taxonomy' => 'product_cat',
      'orderby' => id,
      ); 
      $cates = get_categories( $args ); 
      foreach ( $cates as $cate ) {  ?>
    <option value="<?php echo $cate->slug; ?>"><?php echo $cate->name; ?></option>
  <?php } ?>
 </select>
 <button type="submit" class="btn btn-primary">Tìm kiếm</button>
</form>

9. Code lấy tất cả hình ảnh gallery của sản phẩm.

<?php
  global $product;
  $attachment_ids = $product->get_gallery_attachment_ids();
 foreach( $attachment_ids as $attachment_id ) {
    echo $image_link = wp_get_attachment_url( $attachment_id );
 }
?>

10. Code lấy phần trăm giảm giá của sản phẩm.

<?php if($product->is_on_sale() && $product->product_type == 'simple') : ?>
  <span class="label right label-info">
    <?php  $percentage = round( ( ( $product->regular_price - $product->sale_price ) / $product->regular_price ) * 100 );
           echo $price . sprintf( __('%s', 'woocommerce' ), $percentage . '%' ); ?>
  </span>
<?php endif; ?>

11. Code lấy nội dung mô tả ngắn, category, từ khóa của sản phẩm.

<?php echo apply_filters( 'woocommerce_short_description', $post->post_excerpt ) ?>
// Lấy mô tả ngắn sản phẩm
<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Chuyên mục:', 'Chuyên mục:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>
// lấy chuyên mục sản phẩm
<?php echo $product->get_tags( ', ', '<span class="tagged_as">' . _n( 'Từ khóa:', 'Từ khóa:', $tag_count, 'woocommerce' ) . ' ', '.</span>' ); ?>
// Lấy từ khóa sản phẩm

Nhưng đoạn code này chèn ở file single-product.php nhé!

12. Code lấy 10 sản phẩm liên quan.

global $product, $woocommerce_loop;

if ( empty( $product ) || ! $product->exists() ) {
 return;
}

$related = $product->get_related( $posts_per_page );

if ( sizeof( $related ) === 0 ) return;

$args = apply_filters( 'woocommerce_related_products_args', array(
 'post_type'            => 'product',
 'ignore_sticky_posts'  => 1,
 'no_found_rows'        => 1,
 'posts_per_page'       => 10,
 'orderby'              => $orderby,
 'post__in'             => $related,
 'post__not_in'         => array( $product->id )
) );

$products = new WP_Query( $args );

$woocommerce_loop['columns'] = $columns;

if ( $products->have_posts() ) : ?>

 <div class="related block-product">

  <h3 class="title-related"><?php _e( 'Related Products', 'woocommerce' ); ?></h2>

  <?php woocommerce_product_loop_start(); ?>

   <?php while ( $products->have_posts() ) : $products->the_post(); ?>

   <?php global $product; ?>
<li>
 <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(); ?>
</li>

   <?php endwhile; // end of the loop. ?>

  <?php woocommerce_product_loop_end(); ?>

 </div>

<?php endif;

wp_reset_postdata();

Chèn code này vào phần dưới của file single-product.php

13. Code chèn share và like facebook, google cho chi tiết sản phẩm.

function woo_share_and_ontact_hk(){ ?>
 <div class="social-product">
  <div class="fb-like" data-href="<?php the_permalink(); ?>" data-layout="button_count" data-action="like" data-show-faces="true" data-share="true"></div>
  <script src="https://apis.google.com/js/platform.js" async defer></script>
    <g:plusone size="medium"></g:plusone>
 </div>
<?php }
add_action('woocommerce_single_product_summary', 'woo_share_and_ontact_hk', 60);

Chèn vào file functions.php nhé

14. Code chèn 5 sao cho sản phẩm hiện thị ở chi tiết sản phẩm.

function woo_star_hk(){ ?>
 <p class="ster">
  <span><i class="fa fa-star"></i></span>
  <span><i class="fa fa-star"></i></span>
  <span><i class="fa fa-star"></i></span>
  <span><i class="fa fa-star"></i></span>
  <span><i class="fa fa-star"></i></span>
 </p>
<?php }
add_action('woocommerce_single_product_summary', 'woo_star_hk', 7);

Chèn vào file functions.php nhé, và dùng với thư viện font icon nhé!.

15. Code support template woo

function my_custom_wc_theme_support() {
    add_theme_support( 'woocommerce' );
}
add_action( 'after_setup_theme', 'my_custom_wc_theme_support' );
Huy Kira

Đam mê hóa học, ưng thi vào trường kinh tế... Đậu vào trường Sư phạm, quyết tâm đi dạy... Ra trường đi làm designer, tự học frontend, chuyển qua làm PHP, được công ty đào tạo laravel... Và hiện tại đang code react native(2015) => Fullstack ... ?? tối về viết blog... (Còn tiếp...)

View Comments

Recent Posts

Cafe với Anh Huy nghe kể chuyện hành trình fonttiengviet.com

Fonttiengviet.com là một dự án website do JKS thực hiện cho khách hàng Huy Academy.…

9 tháng ago

Giới thiệu thiết kế web Quảng Nam Web – quangnamweb.com

Chắc chắn nhiều anh em khi đọc bài viết này sẽ nghĩ tôi đang quảng…

9 tháng ago

Hướng dẫn viết widget bài viết theo chuyên mục trong wordpress

Widget trong WordPress là một công cụ mạnh mẽ cho phép bạn dễ dàng thêm…

11 tháng ago

Tạo website để viết blog với chi phí thấp nhất ai cũng làm được

Hôm nay mình sẽ hướng dẫn cho anh em cách tạo website blog cực kỳ…

11 tháng ago

WordPress có cùi bắp? Có sống tốt với nghề thiết kế website wordpress?

Sống cực tốt anh em ạ :D Sau nhiều năm gắng bó với nghề thiết…

12 tháng ago

Share mẫu website blog cá nhân cực nhẹ, giống hocwordpress.vn

Nhân dịp quay lại viết blog mình share cho anh em code mẫu website blog…

12 tháng ago