I would like to groupe WP post (from ‘dlm_download’ post type by values from an acf field ‘telechargement_type_fichier’.
Value 1 : Post 1 Post 2 Post 3
Value 2 : Post 4 Post 5 Post 6
Value 3 : Post 7 Post 8 Post 9
…
Here’s my code :
$field_posts = array();
$args = array(
'post_type' => 'dlm_download',
'post_status' => 'publish',
);
$query = new WP_Query($args);
while ( $query->have_posts() ) {
$query->the_post();
$field = get_post_meta(get_the_ID(), 'telechargement_type_fichier',true);
$field_posts[$field][] = $post;
}
wp_reset_query();
foreach ($field_posts as $field_post => $field_title) {
echo '<p style="font-weight:bold;">' . esc_html($field_post) . '</p>';
foreach ($field_title as $post_listing => $listing)
{ setup_postdata($listing);
$id = get_the_id();
$title = get_the_title($id);
var_dump($title);
}
wp_reset_postdata();
}
However, here’s the result I obtain :
Value 1 – programme_scolaire
Post 1 – Title
Post 1 – Title
Post 1 – Title
Value 2 – module
Post 1 – Title
Value 3 – flyer
Post 1 – Title
Post 1 – Title
Value 4 – jeu
Post 1 – Title
Post 1 – Title
Post 1 – Title
Post 1 – Title
I obtain the real posts number by existing values field but same post/title into the loop.
May be post id error or "reset_postdata()"… Don’t understand why.
Could you help me ?
Thanks !
2
Answers
I found the solution.
Making an array :
Making a query with posts you would like to filter by field value and calling the ACF field and value you want to display.
Making a foreach loop into a foreach loop to classify each post per field value
I obtain :
Field value 1
Post 1
Post 2
Field value 2
Post 3
Post 4
etc .........
I’m not super familiar with PHP/Wordpress, but I think your inner foreach should look like this:
Or