WordPress企业主题开发中会使用到相关产品推荐,方便用户从当前页面跳转到其他产品页面,增加用户的购买兴趣,但是不是所有的WordPress主题带产品功能推荐,那么如何为WordPress主题添加相关产品推荐?
今天推荐大家一个常用的推荐同分类目录下文章的代码方式,只要将代码**到文章底部,并对应添加我们的css样式就可以了,可以**设置推荐文章数量和列表形式。代码如下:
<?php
//get the taxonomy terms of cus*** post type
$cus***TaxonomyTerms = wp_get_object_terms( $post->ID, ‘product_category’, array(‘fields’ => ‘ids’) );
//query arguments
$args = array(
‘post_type’ => ‘products’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => 4,
‘orderby’ => ‘rand’,
‘tax_query’ => array(
array(
‘taxonomy’ => ‘product_category’,
‘field’ => ‘id’,
‘terms’ => $cus***TaxonomyTerms
)
),
‘post__not_in’ => array ($post->ID),
);
//the query
$relatedPosts = new WP_Query( $args );
//loop through query
if($relatedPosts->have_posts()){
echo ‘<div class=”related-products”>’;
echo ‘<h3>’ . __(‘Related Products’) . ‘</h3>’;
echo ‘<ul>’;
while($relatedPosts->have_posts()){
$relatedPosts->the_post();
?>
<li>
<a href=”https://www.wpzt.net/<?php the_per**link(); ?>”><?php the_post_thumbnail(‘product_thumb’); ?></a>
<a href=”https://www.wpzt.net/<?php the_per**link(); ?>”><?php the_title(); ?></a>
</li>
<?php
}
echo ‘</ul></div>’;
}else{
//no posts found
}
//restore original post data
wp_reset_postdata();
?>
暂无评论内容