Support

Account

Home Forums Front-end Issues Querying user connected to a custom post type via relationship field

Solving

Querying user connected to a custom post type via relationship field

    • wallyhp

    • July 10, 2019 at 10:21 pm

    I have set up a custom post type & then custom user roles. When on a particular custom post type page I want to show the users which are connected to the custom post type. I went through the querying relationship fields article (doctors/locations) and based the below on that plus some other snippets however, no matter what custom post you go to it shows all users. Here’s what I have now:

    $args = array(
    ‘role’ => ‘Attorneys’,
    ‘key’ => ‘service_areas’, // name of custom field
    ‘value’ => ‘”‘ . $post->ID . ‘”‘, // matches exactly “123”, not just 123. This prevents a match for “1234”
    ‘compare’ => ‘LIKE’
    );

    // The User Query
    $user_query = new WP_User_Query( $args );
    // The User Loop
    if ( ! empty( $user_query->results ) ) { ?>
    <h2>Attorneys</h2>
    <?php foreach ( $user_query->results as $user ) {
    echo ‘user_nicename ) .'”>’. esc_attr( $user->display_name ) .’<br>’;
    }
    } else {
    echo ‘nope’;
    }
    ?>

    I thought I had it all set up until this morning when I added some more of the custom post types & the users were still showing even through they weren’t assigned to the particular post type in question. Any guidance would be appreciated.

  • 
    $args = array(
      'role' => 'Attorneys',
      'meta_query' => array(
        array(
          'key' => 'service_areas', // name of custom field
          'value' => '"' . $post->ID . '"', // matches exactly "123", not just 123. This prevents a match for "1234"
          'compare' => 'LIKE'
        )
      )
    );
    
  • Awesome, thank you John. Now that I’m seeing it I should’ve figured it out myself. Another pair of eyes always helps. Thanks again!

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

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.