Support

Account

Home Forums Front-end Issues Query CPT from relationship field in regular post

Helping

Query CPT from relationship field in regular post

  • Edit – never mind. I figured this out…

    I’m working on a project that uses the relationship field from v4.4.11 and I’m having a hard time getting the result I want. The project is a magazine where each is issue is a CPT of issue, and each article is a regular post. Each issue collects a bunch of articles via a relationship field. Each article selects one issue via a relationship field.

    What I need to do is find the issue that an article belongs to so that I can display the issue name in a nav element while a visitor is reading the single article. The problem is that if I try this, I get every issue not just the one I want.

    
    $query = get_posts(array(
      'post_type' => 'post',
      'meta_query' => array(
        'key' => 'issue',
        'value' => '"' . get_the_ID() . '"',
        'compare' => 'contains' // or anything else
      )
    ));
    

  • 1) I believe the compare word you are looking for is LIKE.
    2) meta_query takes nested array, so your code should be like

    
    $query = get_posts(array(
        'post_type' => 'post',
        'meta_query' => array(
            array(
                'key' => 'issue',
                'value' => '"' . get_the_ID() . '"',
                'compare' => 'LIKE'
            )
        )
    ));
    

    https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

    Cheers

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

The topic ‘Query CPT from relationship field in regular post’ is closed to new replies.