Search code examples
wordpresswordpress-rest-api

How to use WP_Query to get nested values of an object?


I have searched a lot online with no luck on searching nested values

lets say i have a users array

[
{
 id: 0,
 billing: {
  phone: "999999"
 }
},
{
 id: 1,
 billing: {
  phone: "777777"
 }
}
]

I want to use WP_Query to filter by phone number is it possible to do that ? and how ?

function get_customers(WP_REST_Request $request) {
        $param = $request['phone'];

        $args = array(
            'post_type' => 'customer',
            'posts_per_page' => 1,
            'meta_query' => array(
                'key'     => 'billing.phone',
                'value'   => $param,
                'compare' => '='
            )
        );

        $customers = new WP_Query($args);
        return $customers->posts;
    }

add_action( 'rest_api_init', function() {
    register_rest_route('rc/v1', 'customers/(?P<phone>\d+)', [
        'methods' => 'GET',
        'callback' => 'get_customers'
    ]);
});

Solution

  • First, your meta_query syntax is wrong it's should be inside one more array check here and If your post meta key is 'billing.phone' then the below code will work fine.

    function get_customers( WP_REST_Request $request ) {
    
        $param = $request['phone'];
    
        $args = array(
            'post_type'      => 'customer',
            'posts_per_page' => 1,
            'meta_query'     => array(
                array(
                    'key'     => 'billing.phone',
                    'value'   => $param,
                    'compare' => '='
                )
            )
        );
    
        $customers = new WP_Query($args);
        return $customers->posts;
    }
    
    add_action( 'rest_api_init', function() {
        register_rest_route('rc/v1', 'customers/(?P<phone>\d+)', [
            'methods'  => 'GET',
            'callback' => 'get_customers'
        ]);
    });