How to query related posts in a 3 way relationship

Support MB Relationships How to query related posts in a 3 way relationship

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #44680
    GlennGlenn
    Participant

    Hi Guys,

    I have 3 CPTs, Service, Sector and Project. Project is related to both Service and Sector as a one to many (i.e. A project can have multiple services and sectors)

    I'm stuck trying to figure out how I can display related projects on my project page (i.e. any project connected to any of the same services or sectors that the current project is connected to).

    Any ideas how to do this?

    Thanks

    #44686
    PeterPeter
    Moderator

    Hello Glenn,

    You need to use two loops to achieve the goal. Here is an example:
    - First loop: get the sectors that are related to the current project.
    - Nested second loop: get the projects that are related to the current sector except the current project in the first loop.
    Please follow this ticket https://support.metabox.io/topic/traversing-multiple-related-cpts/

    #44692
    GlennGlenn
    Participant

    Hi Peter,

    Thanks for the prompt reply. I did have a look at that support article before I posted this and was hoping there might be another way but it seems there isn't. I'll probably go down a different route as this could be very inefficient as a project could potentially (albeit unlikely) be related to 9 services and 9 sectors resulting in 20 queries.

    I'm thinking I might just use taxonomies to achieve this. (Being a little lazy now) Is there a hook that can trigger when relationships are selected on the post ( that I could use to assign an identically named taxonomy ). I'm thinking I could then use something like BricksExtras "Related Posts" feature to quickly grab posts with matching taxonomies.

    Kind regards,
    Glenn

    #44705
    PeterPeter
    Moderator

    Hello,

    If you use the taxonomy, you can use one WP query with the parameters tax_query and post__not_in to get all posts that have the same term and exclude the current post.
    Please follow WordPress query documentation https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.