Home Forums General Issues Multiple (pluralized) relationships in a single query


Multiple (pluralized) relationships in a single query

  • Let me preface this by saying that while I am a software engineer, I’m just getting my feet wet in WordPress development.

    My site has two uses of ACF for board games.

    1) Writers can select a single board game which creates a record in wp_postmeta with a meta_key of board_game and a meta_value of a single related post_id.
    2) I _want_ writers to be able to select multiple board games. I just added that feature this morning and it writes a record to wp_postmeta with a meta_key of board_games and a meta_value of a JSON blob. As you can see from the image below both records are available in a raw SQL query.

    Is it possible to retrieve all occurrences of a given post_id from two relationships in a single query? Perhaps something like this?

    $posts = get_field('board_game', 'board_games');

    The goal is that for a given board game, Catan for example, I would be able to retrieve every post on my site which ever mentioned Catan; whether as a single entry or as past of a multi-select box.

  • First, the value in the DB is not a JSON value, it is a serialized array, but that does not matter.

    In order to get all posts with a value, first you need to know the post ID of the value you’re looking for, then using this value you need to do a WP_Query to get the posts.

    I’m only including the meta_query portion of the query args

    'meta_query' => array(
      'relation' => 'OR',
        'key' => 'board_game',
        'value' => $post_id
        'compare' => '='
        'key' => 'board_games',
        'value' => '"'.$post_id.'"',
        'compare' => 'LIKE'

    see, and

  • John, thanks for taking the time to respond. Let me answer some of your questions, and ask a few of my own.

    1) There’s already a page on my site for this, but I’m looking to add functionality to it:
    2) $post->ID is already available on the page.

    I’ll take a look at the code examples you linked to and see if I can hash it out. Thank you.

  • Let me know if you have any questions. I could probably have explained everything but it would have been a very long explanation where everything is already written.

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Multiple (pluralized) relationships in a single query’ is closed to new replies.