wordpress - WordPress - 获取每个用户的帖子
问题描述
对于一个学生项目,我使用 WordPress 和 Timber (TWIG) + ACF
为了这个项目,我创建了 3 种自定义帖子类型dissertation
:subject-imposed
和subject-free
每个学生只能通过自定义帖子类型创建一个帖子(我为此创建了一个限制)。
但现在我想显示一个包含每个学生姓名和他们的 3 个帖子的列表。
像这样的列表:
尼古拉斯·梅普尔
- 自定义帖子类型标题
dissertation
+自定义帖子类型名称+图片(ACF字段) - 自定义帖子类型标题
subject-imposed
+自定义帖子类型名称+图片(ACF字段) - 自定义帖子类型标题
subject-free
+自定义帖子类型名称+图片(ACF字段)
布伦达·史密斯
- 自定义帖子类型标题
dissertation
+自定义帖子类型名称+图片(ACF字段) - 自定义帖子类型标题
subject-imposed
+自定义帖子类型名称+图片(ACF字段) - 自定义帖子类型标题
subject-free
+自定义帖子类型名称+图片(ACF字段)
首先,我尝试获取每个学生的 ID:
$students = get_users( array(
'role' => 'student',
'orderby' => 'user_nicename',
'order' => 'ASC',
'has_published_posts' => true
));
$students_id = array();
foreach ($students as $student) {
$students_id[] = $student->ID;
}
从这些 ID 获取所有帖子后:
$get_posts_students = get_posts( array(
'author' => $students_id,
'post_type' => array('dissertation', 'subject-imposed', 'subject-free')
));
$context['list_of_students'] = $get_posts_students;
我收到了错误urldecode() expects parameter 1 to be string
和一个数组,但所有帖子都没有按学生分组
请问我可以帮忙吗?如何按学生分组帖子?
更新 - 更好但不完整(@disinfor 的解决方案):
在get_posts
foreach 中,我将帖子分组。但我没有每个小组中学生的姓名。
$students = get_users( array(
'role' => 'student',
'orderby' => 'rand',
'has_published_posts' => true
));
$students_posts = array();
foreach ($students as $student) {
$students_posts[] = get_posts( array(
'author' => $student->ID,
'post_type' => array('dissertation', 'subject-imposed', 'subject-free')
));
}
$context['students_posts'] = $students_posts;
解决方案
您可以使用以下方法将学生的姓名包含在数组中get_user_meta()
:
foreach ($students as $student) {
// Get the first name from user meta.
$first_name = get_user_meta( $student->ID, 'first_name');
// Get the last name from user meta.
$last_name = get_user_meta( $student->ID, 'last_name');
// Add a new array key for "name". The first name and last name return as arrays, so we use [0] to get the first index.
$students_posts['name'] = $first_name[0] . ' ' . $last_name[0];
$students_posts[] = get_posts( array(
'author' => $student->ID,
'post_type' => array('dissertation', 'subject-imposed', 'subject-free')
));
}
$context['students_posts'] = $students_posts;
推荐阅读
- coq - Coq:有什么方法可以避免对 sort Set 进行案例分析?
- android - 抱怨在android运行时找不到.so(sharedlibraries)文件
- numpy - 反射/镜像填充如何工作?在numpy还是一般?
- spring-boot - application.properties 中 spring.data.elasticsearch.properties 的可能值
- java - 使用 Java API 绕过垃圾箱从 HDFS 中删除文件
- jquery - 可以在与当前不同的数组中找到先前的数字吗?
- java - 如何从 Mathpix API 字符串响应中获取方程
- javascript - JavaScript:停止执行直到延迟结束
- windows - 编写一个批处理(.bat)文件,可以一个一个地执行多个命令
- java - 更改 EditTextPreference 对话框输入文本颜色