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.
Screenshot:
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
Okay, so the
user_address
in your table is not a key, it is the value ofmeta_key
. Your end result, thinking logically, is that you want themeta_value
of ameta_key
that has the value ofuser_address
.One way to do this, to change the foreach loop in php to:
Now, if you dump that array, it will look like:
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 asdata.user_address
, because the array dump will now look like:I have found a solution.
Changed from
to
Then i’ve changed :
to
and data[i] becomes data[i].meta_value