Reputation: 625
For a project with students I use WordPress with Timber (TWIG) + ACF
Fot this project I created 3 custom post types : dissertation
, subject-imposed
and subject-free
Each student can create only ONE post by custom post type (I created a restriction for that).
But now I would like to display a list with the name of each student and their 3 posts.
A list like that :
Nicolas Mapple
dissertation
+ custom post type name + image (ACF field)subject-imposed
+ custom post type name + image (ACF field)subject-free
+ custom post type name + image (ACF field)Brenda Smith
dissertation
+ custom post type name + image (ACF field)subject-imposed
+ custom post type name + image (ACF field)subject-free
+ custom post type name + image (ACF field)To begin I tried to get the ID of each student :
$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;
}
After to get all posts from these 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;
I got the error urldecode() expects parameter 1 to be string
and an array but with all posts, not grouped by student
Can I have some help please ? How to group posts by student ?
With the get_posts
in the foreach I got posts grouped. But I don't have the name of the student in each group.
$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;
I got an array like that, I would like the name of the student in each group :
Upvotes: 1
Views: 303
Reputation: 11533
You can include the student's name into the array using 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;
Upvotes: 0