Question

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

  • Title of custom post type dissertation + custom post type name + image (ACF field)
  • Title of custom post type subject-imposed + custom post type name + image (ACF field)
  • Title of custom post type subject-free + custom post type name + image (ACF field)

Brenda Smith

  • Title of custom post type dissertation + custom post type name + image (ACF field)
  • Title of custom post type subject-imposed + custom post type name + image (ACF field)
  • Title of custom post type 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 ?

Was it helpful?

Solution

According to the WP_Query::parse_args docs (which is what parses the $args you're passing to get_posts()), the $author parameter needs to be an int or a string (a comma-separated list of IDs).

But you're also going to need this set up in groups, per student, so here's what I'd recommend: use an array to store each student's posts, then print them out once you've got them all.

$students = get_users( array(
    'role'    => 'student',
    'orderby' => 'user_nicename',
    'order'   => 'ASC'
    'has_published_posts' => true
));

$students_posts = array();

foreach ($students as $student) {
    $get_posts_student = get_posts( array(
        'author' => $student->ID,
        'post_type' => array('dissertation', 'subject-imposed', 'subject-free')
    ));
    $students_posts[ $student->ID ] = array(
        'name'  => $student->user_nicename,
        'posts' => $get_posts_student,
    );
}

This should give you an array of students and their posts that you can then loop through and display.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top