wordpress企业主题开发之相关产品调用代码

本文介绍了在WordPress企业主题开发中,如何在产品详情页底部添加相关产品模块。通过调用自定义分类法“product_category”,使用WP_Query查询同分类下的随机4个产品,并排除当前产品。代码展示了如何循环输出产品缩略图、标题及链接,最后重置查询数据。

文章作者:
阅读时间: 8 分钟
更新时间:2025年11月13日

我们用wordpress开发企业主题的时候,如果有产品展示模块,那在浏览产品详情页的时候,我们经常会看到产品详情底部有一个相关产品显示。其实对于这个模块我们并不陌生,因为在我们写文章详情页的时候,也写过调用当前文章的相关文章代码,在这里我贴一段在wordpress企业主题开发中经常使用的相关产品调用代码。

<?php
			//get the taxonomy terms of custom post type
			$customTaxonomyTerms = 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' => $customTaxonomyTerms
			        )
			    ),
			    '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="<?php the_permalink(); ?>"><?php the_post_thumbnail('product_thumb'); ?></a>
			    	<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
			    </li>
			<?php
			    }
			    echo '</ul></div>';
			}else{
			    //no posts found
			}
			//restore original post data
			wp_reset_postdata();
			?>

 

这篇文章有用吗?

点击星号为它评分!

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

在AI工具中继续讨论:
曾凤祥
曾凤祥
WordPress技术负责人
WordPress 独立站开发领域 10+ 年实践经验,长期专注于外贸独立站搭建与 SEO 优化,累计服务企业客户数百家(含制造业、外贸企业、政府等行业)
相关文章
无论你是否已有网站,我们都能帮你把线上业务推上新高度
无论什么行业,都能快速拥有专业网站:
无论什么行业,都能快速拥有专业网站:

展示型官网 / 品牌站 / 外贸独立站,均有成熟模板与定制方案
无需懂代码:可视化编辑+我们指导,轻松启动 → 快速上线,抢占先机​
结构清晰、利于SEO与后期运营,降低长期维护成本

立即查看建站方案
网站加载慢、跳出高、询盘少?
网站加载慢、跳出高、询盘少?

老旧体验与技术隐患会直接拖累获客与转化。
我们提供:网站全面诊断 → 速度/安全/结构优化 → 可持续运维支持(技术+策略),让网站真正成为您的业务增长工具,而不只是“线上门面”。

马上获取专属优化方案
微信联系
chat 扫码联系
模板建站
挑选模板
网站定制
免费诊断
咨询热线
咨询热线

189-0733-7671

返回顶部