Support

Account

Home Forums Front-end Issues WP_Query with user array field Reply To: WP_Query with user array field

  • Hi! I just found this and it is EXACTLY what I need. Let me explain the scenario:

    I’m creating a shop where customers have access to a page where they can see some products that are assigned to them.

    So, naturally, I created a “User” field for the “product” post type, with the possibility (this is required) to assign multiple users, and to filter them by the “client” role. I assigned my test user to some of my test products and proceeded to create my loop. Here it is:

    <?php
        // The Query
        $args = array(
            'post_type'  => 'product',
            'meta_key'   => 'assign_client',
            'meta_value' => '2'
        );
        $the_query = new WP_Query( $args );
    
        // The Loop
        if ( $the_query->have_posts() ) {
            echo '<ul>';
            while ( $the_query->have_posts() ) {
                $the_query->the_post();
                echo '<li>' . get_the_title() . '</li>';
            }
            echo '</ul>';
        } else {
            // no posts found
        }
        /* Restore original Post Data */
        wp_reset_postdata();
    ?>

    As you can see, the name of my field is “assign_client” and my user’s ID is 2 (I was planning on using get_current_user_id() so it would filter by the logged in user). Evidently, it failed.

    That’s when I found this entry. Now, I understand (I think) the overall idea of the “Relationship” field, what I don’t get is how to assign a user to a post type through it. I changed my “assign_client” field to “Relationship”, but on the product page, all you can select through are post types, not users.

    Can you give me a hint on this? Thank you in advance!
    Francisco