Support » Plugin: Posts 2 Posts » Sort related posts by category

  • Hi,

    I really like this plugin, but I am a bit stuck in how to get the wanted output. Perhaps someone can direct me in the right direction.

    In my website I have several custom post types that all together need to be grouped by another custom post type (called for example: Group). The posts linked to a Group have a category. Now on each single-post page I need to show a sort of index of what items are grouped in this Group and with which the visitor can navigate through the items in this group:

    Group 1
    Category A
    * item 1
    * item 2

    Category B
    * item 3

    Category C
    * item 4
    * item 5

    I have registered a multi-connection in my functions as:

    function my_connection_types() {
    $post_types = array( 'group', 'cpt-1', 'cpt-2','cpt-3','cpt-4' );
    p2p_register_connection_type( array(
    	'name' => 'multi_connections',
    	'from' => $post_types,
    	'to' => $post_types,
    ) );
    add_action( 'p2p_init', 'my_connection_types' );

    And I manage to output the connected posts by:

    <?php $related = p2p_type( 'multi_connections' )->get_related( get_queried_object() );?>

    However, I can’t seem to sort the posts by category as the desired way described above. Perhaps someone can point me in the right direction?

    Thanks a lot!

Viewing 2 replies - 1 through 2 (of 2 total)
  • I don’t think you can do this with the basic plugin.

    Assuming that $related returns an array of posts, I would think that you then need to loop through that array, sorting by category as you go. That is probably a different avenue of enquiry.


    I guess connection meta would help. Let’s say you add ‘group’ as a meta field and then do a separate query for each group. But maybe you can also use taxonomies to sort your cpt.

    Or you just do one query and then as tedinoz explained, loop through that array and sort it by the meta value (or taxonomy) or whatever else you choose.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Sort related posts by category’ is closed to new replies.