php - 根据类别显示随机产品
问题描述
我在一个产品的单个产品页面中。我想展示,在这个产品之后,其他 4 个同类别的随机产品
我只有这个:(PHP)
<?php
global $product;
$terms = get_the_terms( $product->get_id(), 'product_cat' );
var_dump($terms);
$args = array(
'posts_per_page' => 4,
'orderby' => 'rand',
'post_type' => 'product' );
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?></a>
</li>
<?php endforeach;
wp_reset_postdata();
?>
谁能帮我?谢谢
解决方案
你可以试试这个方法。我检查了它的工作:
global $product;
$terms = get_the_terms( $product->get_id(), 'product_cat' );
$first_term = array_shift( $terms );
$args = array(
'posts_per_page' => 4,
'orderby' => 'rand',
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( $first_term->slug )
)
),
'post__not_in' => array( $product->get_id() )
);
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?></a>
</li>
<?php endforeach;
wp_reset_postdata();
?>
推荐阅读
- python - Keras 验证生成器评估指标
- php - 使用私有存储桶授权的 Backblaze Storage B2 PHP 下载
- python - 添加 webdriverwait 功能以加载 href 页面时,Selenium 拒绝连接
- jquery - jQuery slideToggle 使隐藏内容开始和结束BEHIND clicked div
- linux - 通过脚本迭代目录的内容
- node.js - 从数组 mongodb 中查找前 3 个值
- dynamics-crm - 即使具有组织级别的读取权限,查看记录时也会出现权限错误
- angular - Angular 6 单例服务总是在 APP_INITIALIZER 之后重置
- corda - Cordapp 教程在 Fedora VirtualBox 机器中崩溃
- php - 使用 ImageMagick 时如何修复“无法注释图像”错误?