php - 如何显示来自特殊父类别孩子的相关 wordpress 帖子?
问题描述
我在 Wordpress 主题的 Single.php 模板中工作,但在相关帖子中我有问题!
我想显示来自父类别子项的相关帖子,例如我在 Wordpress 中添加名称为 A 的父类别,在这个父类别中,我们有 B、C、D 和其他子类别,可以为 Wordpress 帖子区域中的每个帖子设置。
好吧,我在 D(或其他 A 孩子)类别中发布了新帖子,我想在相关帖子框中显示,其他来自 D(或其他 A 孩子)类别。
这是我的工作,但不好
$related = get_posts( array(
'category__in' => wp_get_post_categories( $post->ID ),
'numberposts' => 3,
'post__not_in' => array( $post->ID )
) );
我是新手,请帮帮我,谢谢。
解决方案
此代码将与父母一起获得分类,因此在您的情况下,它将获得孩子,但如果您可以有一个 A->B 和 A->C 的帖子,它只会从选择的第一个类别中获得相关帖子,例如(A ->B)
$terms = wp_get_post_terms($post->ID, 'category');
if (count($terms)) {
foreach ($terms as $term) {
if ($term->parent != 0) {
$relatedTerm = $term;
break;
}
}
$related = get_posts(array(
'category__in' => $relatedTerm->term_id,
'numberposts' => 3,
'post__not_in' => array($post->ID),
));
}
推荐阅读
- reactjs - 为什么我在 React 中从数据库 Postgresql 加载数据时出现错误?
- r - R - 计算不返回正确答案 0
- python - 使用 python 和 Scikit Learn 为 K-NN 机器学习算法实现 ROC 曲线
- json - jmeter JSON Extractor 无法处理 [
- html - CSS - 将两个 div 浮动在彼此旁边,而不是它们在彼此下方
- java - 我可以在我的自定义 Android 键盘上添加“Ctrl”键吗?
- xcode - React Native:模拟后台获取已禁用
- linux - docker 命令不会在 Debian 中运行
- ghostscript - Ghostscript 9.05 无法使用 pdfwrite 将 PDF 转换为 PDF
- php - 嵌入在html中的php标签是如何真正执行的?