首页 > 解决方案 > WordPress - 获取每个用户的帖子

问题描述

对于一个学生项目,我使用 WordPress 和 Timber (TWIG) + ACF

为了这个项目,我创建了 3 种自定义帖子类型dissertationsubject-imposedsubject-free

每个学生只能通过自定义帖子类型创建一个帖子(我为此创建了一个限制)。

但现在我想显示一个包含每个学生姓名和他们的 3 个帖子的列表。

像这样的列表:

尼古拉斯·梅普尔

布伦达·史密斯

首先,我尝试获取每个学生的 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_postsforeach 中,我将帖子分组。但我没有每个小组中学生的姓名

$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;

我有一个这样的数组,我想要每个组中学生的名字: 在此处输入图像描述

标签: wordpressadvanced-custom-fieldstimber

解决方案


您可以使用以下方法将学生的姓名包含在数组中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;

推荐阅读