0

We have a different custom post types such as 'Paper', 'Publications', 'Events', 'Media'.

When creating a 'Paper' post type, I use a 'Relationship' field of ACF to link to different posts from Publications, Events, and other post types. Similarly, when I create a Publication post_type, I will be linking to 'Paper', 'Events', 'Media'.

On the detail page of the new Paper post just created above, I'm able to list all linked posts through Relationship but I'm not able to group them together by their post type. E.g if I linked 3 Publications, 2 Media post types, and 2 Events post type to the Paper post.

Publications

1-
2- 
3- 

Media

1-
2-

Events

1-
2- etc

When I exported the Paper post I see the details how relationship values are being stored below:

<wp:meta_key><![CDATA[relationship]]></wp:meta_key>
        <wp:meta_value><![CDATA[a:10:{i:0;s:4:"4014";i:1;s:4:"2656";i:2;s:4:"3933";i:3;s:4:"3929";i:4;s:4:"3967";i:5;s:4:"4018";i:6;s:4:"1409";i:7;s:4:"1391";i:8;s:4:"4036";i:9;s:4:"4033";}]]></wp:meta_value>

If you noticed, all the linked posts are stored as IDs with numbering as i:0, i:1, i:2 etc.

Here is the code I have below through which I'm able to list all posts:

<?php $posts = get_field('relationship'); //relationship is the Relationship fiel type

 if( $posts ):

 foreach( $posts as $post): 

     setup_postdata($post);

     if ($post->post_type == "publications") {?>

      }
     if ($post->post_type == "events") {?>

      }

If I do the above code, it checks if the post_type is publications but I need to group the posts by post_type and list them. Do I need to run another loop inside the if post->post_type?

  • to group by post type, you can make a first loop to store them in a PHP associative array ($tab[$post->post_type][] = $post;) and then a 2nd loop to display the list of posts. – mmm Apr 30 '18 at 13:52
  • I was able to achieve through another script but I'm not able to show the code here. Do not know why! – Rakesh Ojha May 1 '18 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.