Custom Fields
Re-Envisioned
Support MB Relationships Trouble with relationship query in pre_get_posts

  • Creator
    Topic
  • #32728
    Resolved papertower
    Participant

    Greetings!

    I have the following code inside of a pre_get_posts action:

    
        if (false !== get_query_var(SERVICE_VAR, false)) {
            $service = Service::get_controller();
            if ($service instanceof Service) {
                $query->set('relationship', [
                    'id' => get_relation_id('post', SERVICE_TYPE),
                    'to' => $service->id
                ]);
            }
        }
    
    

    This is being used on the post archive (blog) in the main query. I've stepped through the code in XDebug and can confirm that the relationship query is being added, but it doesn't appear to be working. I'm actually switching from Piklist to Meta Box, and the old Piklist query modifier works, so I know the code overall is working; the Meta Box relationship is not working. I've double-checked that the relationships and such are in place.

    Is there something distinct I need to do in pre_get_posts? Or do I need to make sure my hook is at a certain priority?

    Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Author
    Replies
  • #32729
    papertower
    Participant

    After further digging, it looks like the Meta Box Relationships plugin uses the parse_query action which happens before pre_get_posts. That explains why it wasn't working.

    I switched the action I was using from pre_get_posts to parse_query and that resolved the issue.

    It may be worth including in your docs that parse_query or earlier must be used in order to modify a query into supporting relationships.

    #32741
    Long Nguyen
    Moderator

    Hi,

    Thanks for sharing your solution.

    Actually, the action pre_get_posts is fired before parse_query that's why the query var relationship does not work. See https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-query.php#L1804-L1814

    I will note this case in the documentation for other users if they want to filter the main query.

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