WooCommerce 已经是 WordPress 平台最好最强大的在线商城插件,已经被 WordPress 收购,更新速度比较频繁,功能更加完善。本文章主要介绍了 WooCommerce 特色产品循环作为模板标记和短代码以及相关的经验技巧。

在频繁的更新后,一些常用的函数都在优化,一些字段也有所改变。比如获取的是商店特色产品,我们是可以通过以下代码就可以获取特色产品:
<?php$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN',
),
) );
$featured_product = new WP_Query( $args );
if ( $featured_product->have_posts() ) :
echo '<div class="woocommerce columns-3"><ul class="products">';
while ( $featured_product->have_posts() ) : $featured_product->the_post();
$post_thumbnail_id = get_post_thumbnail_id();
$product_thumbnail = wp_get_attachment_image_src($post_thumbnail_id, $size = 'full');
$product_thumbnail_alt = get_post_meta( $post_thumbnail_id, '_wp_attachment_image_alt', true );
?><li class="product">
<a href="<?php the_permalink();?>">
<img src="<?php echo $product_thumbnail[0];?>" alt="<?php echo $product_thumbnail_alt;?>">
<h3 class="woocommerce-loop-product__title"><?php the_title();?></h3>
<button class="yellow-but">VIEW PRODUCT</button>
</a>
</li>
<?php endwhile;
echo '</ul></div>';
endif;
wp_reset_query();
?> <!-- Featured products loop -->

如果你需要在任意地方调用,可以使用 WordPress 的简码 功能,代码如下:
<?phpadd_shortcode( 'woo_featured', 'wb_woo_featured' );
/* * * Featured Product Loop */function wb_woo_featured() {
$args = array(
'post_type' => 'product',
'posts_per_page' => 3,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN'
),
),
);
$featured_product = new WP_Query( $args );
if ( $featured_product->have_posts() ) :
ob_start();
echo '<div class="woocommerce columns-3"><ul class="products">';
while ( $featured_product->have_posts() ) : $featured_product->the_post();
$product = wc_get_product( $featured_product->post->ID );
$post_thumbnail_id = get_post_thumbnail_id();
$product_thumbnail = wp_get_attachment_image_src($post_thumbnail_id, $size = 'shop-feature');
$product_thumbnail_alt = get_post_meta( $post_thumbnail_id, '_wp_attachment_image_alt', true );
// Featured Post Loop Output // wc_get_template_part( 'content', 'product' ); ?><li class="product">
<a href="<?php the_permalink();?>">
<img src="<?php echo $product_thumbnail[0];?>" alt="<?php echo $product_thumbnail_alt;?>">
<h3 class="woocommerce-loop-product__title"><?php the_title();?></h3>
<button class="yellow-but">VIEW PRODUCT</button>
</a>
</li>
<?phpendwhile;
echo '</ul></div>';
endif;
wp_reset_query();
return ob_get_clean();
}专业提供WordPress主题安装、深度汉化、加速优化等各类网站建设服务,详询在线客服!
