Home > Net >  WordPress get_users meta_query search object value
WordPress get_users meta_query search object value

Time:06-17

I'm running a query on users and want to include only users who have meta data (page_history) with a specific value. The problem I'm having is that the meta data is an object, and I can't seem to get the query to check the value of the object:

$role = isset($_GET['role'] && $_GET['role'] !== '');

$args = array(
    'role'    => $role ?? '',
    'orderby' => 'user_nicename',
    'order'   => 'ASC',
    'meta_query' => array(
        'relation' => 'OR',
        $search_term[0] ? array(
            'key'     => 'first_name',
            'value'   => $search_term[0],
            'compare' => 'LIKE'
        ) : '',
        $search_term[1] ? array(
            'key'     => 'last_name',
            'value'   => $search_term[1],
            'compare' => 'LIKE'
        ) : '',
        array(
            'key'     => 'page_history',
            'value'   => 'custom_post_type',
            'compare' => 'EXISTS'
        )
    ),
);

$users = get_users($args);

foreach ($users as $user) {
  
    // Do stuff
  
}

Here is my meta object:

Array
(
    [date] => 1655387457
    [post-type] => custom_post_type
    [page] => Page title here
)

So I just want to get users if they have the meta data page_history set as 'custom_post_type'.

Thank you

CodePudding user response:

This meta object will be serialized before being stored in the database column. The post-type field after serialization will be like that in DB s:9:"post-type";s:16:"custom_post_type";

You can use LIKE compare to filter it.

array(
    'key'     => 'page_history',
    'value'   => 's:9:"post-type";s:16:"custom_post_type";',
    'compare' => 'LIKE'
)

You will need to change the number 16 to the custom post type name count.

  • Related