user7342807
user7342807

Reputation: 313

How to search for users in WP with serialized meta values

I can get users using $all_users = get_users(['meta_key' => 'first_name', 'meta_value' => 'john']); but I have a small problem now, as the meta value for feature I am trying to fetch is serialized.

I have copied a row from the table as shown below.

103  wp_capabilities       a:1:{s:12:"cs_candidate";b:1;}  

I can get the value and unserialize it, but not sure if there is a way to do this in WP.

UPDATE:

To add more clarification, I am referring to this page https://codex.wordpress.org/Function_Reference/get_users or the below function to be exact:

<?php $args = array(
    'blog_id'      => $GLOBALS['blog_id'],
    'role'         => '',
    'role__in'     => array(),
    'role__not_in' => array(),
    'meta_key'     => '',
    'meta_value'   => '',
    'meta_compare' => '',
    'meta_query'   => array(),
    'date_query'   => array(),        
    'include'      => array(),
    'exclude'      => array(),
    'orderby'      => 'login',
    'order'        => 'ASC',
    'offset'       => '',
    'search'       => '',
    'number'       => '',
    'count_total'  => false,
    'fields'       => 'all',
    'who'          => ''
 ); 
get_users( $args ); ?>

The 'meta_value' => '', part in the field is serialized a:1:{s:12:"cs_candidate";b:1;}

Upvotes: 0

Views: 1037

Answers (1)

yivi
yivi

Reputation: 47318

You can't search unserialize an search at the same time, I'm afraid. Searching in serialized data is always a bit of a hassle.

If you are certain of structure of the data you are searching, you could do something like:

$meta_args = [
        'key'     => 'wp_capabilities',
        'value'   => 'cs_candidate";b:1',
        'compare' => 'LIKE'
    ];

$users = get_users(['meta_query' => $meta_args]);

It's anything but pretty, but should do the trick.

Upvotes: 1

Related Questions