How to get meta_key and its meta_value within wp_usermeta by ajax call (json format)

In WordPress I have created some custom fields within my Theme Edit Profile page which, one of them, allows me to enter a user address.
This address is automatically stored in WordPress DB under table wp_usermeta. (custom field is called user_address).

From wp_usermeta, the column called meta_key has a value ‘user_address’. But the content I”m trying to collect is its meta_value equivalent.

Read More

Screenshot:

enter image description here

Here my php code to convert the data into JSON format:

...... 
$row=$db->prepare('select * from wp_usermeta'); 
......

foreach($row as $rec)//foreach loop  
   {  
     $json_array['meta_key']=$rec['meta_key'];
     array_push($json_data,$json_array); 
   }

From the JS file:

request('file.php', function(data) {

  var data = JSON.parse(data.responseText);

  for (var i = 0; i < data.length; i++) {
       console.log(data[i].meta_key);
  }
........

My problem is here. From data[i] I need to get all the ‘user_address’ (within meta_key) and the equvalent value stored in meta_value as shown in the screeshot above, but unfortunately I don’t know how to get it.
I can get all the meta_key values, but I don’t know how to associate user_address to meta_value.

I’ve tried:

data[i].meta_key.user_address.meta_value
data[i].user_address.meta_value
data[i].meta_key[user_address].meta_value
data[i].meta_key['user_address'].meta_value

Any suggestions?
Thanks

Related posts

Leave a Reply

2 comments

  1. Okay, so the user_address in your table is not a key, it is the value of meta_key. Your end result, thinking logically, is that you want the meta_value of a meta_key that has the value of user_address.

    One way to do this, to change the foreach loop in php to:

    foreach($row as $rec)
        {
            $json_array[$rec['meta_key']]=$rec['meta_value'];
            array_push($json_data,$json_array);
        }
    

    Now, if you dump that array, it will look like:

    array(
        ...
        [10] => array (
            'user_address' => '26 Aorile Costo'
        ),
        ...
    )
    

    And you can reference to it in javascript with data[i].user_address

    You could also get rid of the array_push, and just output the $json_array, so you wont have to walk the array in javascript, and can reference to it simply as data.user_address, because the array dump will now look like:

    array(
        ...
        'user_address' => '26 Aorile Costo',
        ...
    )
    
  2. I have found a solution.
    Changed from

    $row=$db->prepare('select * from wp_usermeta');
    

    to

    $row=$db->prepare('select * from wp_usermeta where meta_key = "user_address"')
    

    Then i’ve changed :

    $json_array['meta_key']=$rec['meta_key'];
    

    to

    $json_array['meta_value']=$rec['meta_value'];
    

    and data[i] becomes data[i].meta_value