• Resolved vincent7892

    (@vincent7892)


    Hi everybody,

    I’m trying to get custom user metadata (that i set when someone subscribe) by API request.
    For this purpose, I do this thing to get my users metadata en organise it:

    function getUsersMeta() {
    		$myObj = new stdClass();
    		$users = get_users( array( 'fields' => array( 'ID' ) ) );
    		foreach($users as $user){
    			$myObj->rue = get_user_meta($user->ID,'rue',true);
    			$myObj->cp = get_user_meta($user->ID,'cp',true);
    			$myObj->ville = get_user_meta($user->ID,'ville',true);
    			$myObj->structure = get_user_meta($user->ID,'structure',true);
    		}
    		return json_encode($myObj);
    	}

    And then where I kind of “open the route” :

    
    add_action( 'rest_api_init', function () {
    	register_rest_route( 'authors', '/meta', array(
    		  'methods' => 'GET',
    		  'callback' => 'getUsersMeta',
    		) );
    	});

    But for an unknown (to me) reason, what I get is only one user :

    </img>

    And I’d realy like to get all them.

    Also, I’ve got a noob question : is there any way to display final json in anoter way that : \”rue\”:\”20 rue Bechevelin\”, andso… so that it could be nicer when I reveice it in my .js (i think about the {first{“name”: “jack”, “age”: 22}}

    Thanks a lot !!!, any help will be useful, I already tried lots of get_users() combinations and I can’t get where I’m wrong.

    ??

Viewing 1 replies (of 1 total)
  • Thread Starter vincent7892

    (@vincent7892)

    Ok I’ve manage to got both my answer by myself :

    I was not adding each new object in the foreach loop but replacing the one before…
    So :

    function getUsersMeta() {
    		$obj = new stdClass();
    	
    		$users = get_users( array( 'fields' => array( 'ID' ) ) );
    		//var_dump($users);
    		$i = 0;
    		foreach($users as $user){
    			$i = $i + 1;
    			$index = strval( $i );
    
    			$myObj = new stdClass();
    			$myObj->rue = get_user_meta($user->ID,'rue',true);
    			$myObj->cp = get_user_meta($user->ID,'cp',true);
    			$myObj->ville = get_user_meta($user->ID,'ville',true);
    			$myObj->structure = get_user_meta($user->ID,'structure',true);
    
    			$value = "object ".$index;
    			$obj->$value = $myObj;
    		}
    
    		return $obj;
    	}

    About how JSON is written, my data seems to already BE JSON data so I don’t need json_encode() at all.

Viewing 1 replies (of 1 total)
  • The topic ‘Create custom route for API, get only one user’ is closed to new replies.