我们用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%20the_permalink();%20?>"><?php the_post_thumbnail('product_thumb'); ?></a> <a href="<?php%20the_permalink();%20?>"><?php the_title(); ?></a> </li> <?php } echo '</ul></div>'; }else{ //no posts found } //restore original post data wp_reset_postdata(); ?>