Support

Account

Home Forums ACF PRO How to use WP_Query or search multiple user field Reply To: How to use WP_Query or search multiple user field

  • Hi. I have done something similar. I added a field to regular posts where a user can be selected. This is used to ‘mention’ a certain user. On their profile I retrieve the posts again in which they got mentioned.

    See https://internationaldownhillfederation.org/member/emily-pross/
    Halfway down. User is mentioned in these posts.
    What you’re looking at is an author.php archive so this is a separate query because a user is mentioned in those posts, they didn’t write it.

    My profile shows both mentioned and posts I wrote.

    So here we go 🙂

    First of all, Can you add only 1 user per post ??? Looks like it (I can be wrong). Why not make a repeater out of that field with 1 sub field; which is user.

    My field is called tagged_riders.
    This is a repeater with 1 sub-field (member).
    Member is a user object field.

    /**
     * Get posts in which user is mentioned
     * @param bool $user_id
     *
     * @return bool|array
     */
    function get_user_mentions( $user_id = false ) {
        
        if ( false == $user_id ) {
            return false;
        }
    
        global $wpdb;
        $rows = $wpdb->get_results( $wpdb->prepare(
            "
                SELECT *
                FROM {$wpdb->prefix}postmeta
                WHERE meta_key LIKE %s
                AND meta_value = %s
                ", 'tagged_riders_%_member', // meta_name: $ParentName_$RowNumber_$ChildName
            $user_id ) );
        
        if ( $rows ) {
            $post_ids = array();
            foreach ( $rows as $row ) {
                $post_ids[] = intval( $row->post_id );
            }
    
            return $post_ids;
        
        }
        
        return false;
    
    }

    Keep in mind my fields are called tagged_riders with a subfield member. You need to change these to fit your needs.

    Get all post_ids like this: get_user_mentions( $user_id ), where $user_id is the ID you want to check.

    The results is an array of post_ids in which the user liked.

    Hope this helps.