Add Snippet To Project
<?php
function wpturbo_get_custom_meta($post_id, $meta_keys) {
$meta_data = array();
foreach ($meta_keys as $meta_key) {
$meta_value = get_post_meta($post_id, $meta_key, true);
$meta_data[$meta_key] = $meta_value;
}
return json_encode($meta_data);
}
Explanation:
The function wpturbo_get_custom_meta accepts two parameters: $post_id and $meta_keys. $post_id is the ID of the custom post for which we want to retrieve the custom meta data. $meta_keys is an array of custom meta keys that we want to retrieve the values for.
Inside the function, we initialize an empty array called $meta_data to store the meta key and meta field value pairs.
We then loop through each meta key in the $meta_keys array. For each meta key, we use the get_post_meta function to retrieve the meta field value for the specified post ID and meta key. We set the third parameter of get_post_meta to true to ensure that the retrieved value is returned as a single value, rather than an array.
We then add the meta key and meta field value pair to the $meta_data array using the meta key as the key and the meta field value as the value.
Finally, we use json_encode to convert the $meta_data array into a JSON string and return it.
To use this function, you can call it with the desired post ID and an array of custom meta keys. For example:
This will retrieve the custom meta values for the custom post with ID 123 for the specified meta keys, and output the JSON array of meta_key and meta_field_value pairs. Make sure to replace 123 with the actual custom post ID, and customize the $meta_keys array to include the desired meta keys.
