get custom fieds in rest API (meta_key) - wordpress

I have this function to for my custom fields to save in WP data base (this is working and saving):
function notifyem_save_post() {
if(empty($_POST)) return; //why is prefix_teammembers_save_post triggered by add new?
global $post;
update_post_meta($post->ID, "country", $_POST["country"]);
update_post_meta($post->ID, "region", $_POST["region"]);
update_post_meta($post->ID, "time", $_POST["time"]);
update_post_meta($post->ID, "activity", $_POST["activity"]);
}
I want to display them from REST API but only TITLE is showing:
[{"title":"john"},{"title":"xxx"},{"title":"11"}]
This is my code for my REST API GET
function notifyem_rest_get() {
$subscriptions = new WP_Query(array(
'post_type' => 'notifyem'
));
$subscriptionResults = array();
register_rest_route('notifyemAPI/v1', '/subscription', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => array($this, 'getSubscription')
));
}
function getSubscription() {
$subscriptions = new WP_Query(array(
'post_type' => 'notifyem',
'meta_key' => 'country'
));
$subscriptionResults = array();
while($subscriptions->have_posts()) {
$subscriptions->the_post();
array_push($subscriptionResults, array(
'region' => get_field('regi'),
'country' => get_field('country'),
'activity' => get_field('activity'),
'time' => get_field('time')
));
}
return $subscriptionResults;
}
The screenshow below are the fields inserted to my custom post type.
Any ideas how to get the custom fields I created in my REST API?

Try this code
function getSubscription() {
$subscriptions = new WP_Query(array(
'post_type' => 'notifyem',
'meta_key' => 'country'
));
$subscriptionResults = array();
while($subscriptions->have_posts()) {
$subscriptions->the_post();
array_push($subscriptionResults, array(
'region' => get_post_meta(the_ID(), "region", true),
'country' =>get_post_meta(the_ID(), "country", true),
'activity' => get_post_meta(the_ID(), "activity", true),
'time' => get_post_meta(the_ID(), "time", true)
));
}
return $subscriptionResults;
}

Related

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'
]);
});
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'
]);
});

get_posts() does not return featured_image field on Wordpress custom endpoint

Trying to get only the needed data on a custom endpoint in Wordpress. To do so, I am using get_posts() function.
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'pages', [
'methods' => 'GET',
'callback' => 'wl_page',
]);
});
function wl_page() {
$args = [
'numberposts' => 99999,
'post_type' => 'page',
'post_parent' => 0,
];
$posts = get_posts($args);
$data = [];
$data['ID'] = $posts[0]->ID;
$data['title'] = $posts[0]->post_title;
$data['content'] = $posts[0]->post_content;
$data['featured_image'] = $posts[0]->featured_media;
return $data;
}
It should return the ID of the featured image, but get_posts() doesn't even return that field.
get_posts returns array of Post Objects which don't have featured_media property available. Use get_post_thumbnail_id() instead.
See updated code below:
add_action('rest_api_init', function() {
register_rest_route('wl/v1', 'pages', [
'methods' => 'GET',
'callback' => 'wl_page',
]);
});
function wl_page() {
$args = [
'numberposts' => 99999,
'post_type' => 'page',
'post_parent' => 0,
];
$posts = get_posts($args);
$data = [];
$data['ID'] = $posts[0]->ID;
$data['title'] = $posts[0]->post_title;
$data['content'] = $posts[0]->post_content;
$data['featured_image'] = get_post_thumbnail_id( $posts[0]->ID );
return $data;
}

Custom API Wordpress Endpoint fails

{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}
Im trying to determine whats wrong with my code. Ive written a custom api endpoint for wordpress but I get the above error while trying to access the url. My code is as follows:
$this->loader->add_action('rest_api_init', $plugin_public, 'create_api_webhook');
public function create_api_webhook() {
register_rest_route('learn2/v1', '/api/', array(
'methods' => 'GET',
'callback' => array($this, 'learn2_api_webhook')
));
}
public function learn2_api_webhook() {
global $wpdb;
$args = array('post_type' => 'sfwd-courses',
'post_status' => 'publish',
'order' => 'DESC',
'orderby' => 'ID',
);
$loop = new WP_Query($args);
$courses = array();
$lessons = array();
while ($loop->have_posts()) : $loop->the_post();
$mylessons = learndash_get_lesson_list($post->ID);
$lessons = array();
foreach ($mylessons as $lesson) {
$topics = array();
$mytopics = learndash_get_topic_list($lesson->ID, $post->ID);
foreach ($mytopics as $topic) {
$topics[] = array('id' => $topic->ID, 'title' => $topic->post_title);
}
$lessons[] = array('id' => $lesson->ID, 'title' => $lesson->post_title, 'topics' => $topics);
}
$courses[] = array('id' => $post->ID, 'title' => $post->post_title, 'lessons' => $lessons);
endwhile;
return json_encode($courses);
}
Im trying to access the url with:
http://localhost/community_staging/wp-json/learn2/v1/api/ but I get the above error.
Im running the latest wordpress
$this->loader->add_action('rest_api_init', $plugin_public, 'create_api_webhook');
$plugin_public wasn't pointing to the right class.

Batching with Google Places: Is it possible?

I was wondering if it's possible to send batched requests to maps.googleapis.com. As far as I can tell, it isn't.
I was using the Google API Client Library with supports batching, but it's only for www.googleapis.com. I went ahead and hacked it so that I could call the Places API, and it worked fine for normal calls, but when I actually tried to batch them, I got a 404 error:
"The requested URL /batch was not found on this server. That’s all we know."
So it appears that maps.googleapis.com does not support batching, but I wanted to be sure this is true. If anyone knows otherwise, please tell me how. Thanks!
inside google-api-php-client/src/Google/Config.php:
- 'base_path' => 'https://www.googleapis.com',
+ 'base_path' => 'https://maps.googleapis.com',
google-api-php-client/src/Google/Service/Maps.php:
(I added this file to make Places calls possible.)
<?php
class Google_Service_Maps extends Google_Service
{
const MAPS = "https://maps.googleapis.com/auth/maps";
public function __construct(Google_Client $client)
{
parent::__construct($client);
$this->servicePath = 'maps/api/';
$this->version = 'v3';
$this->serviceName = 'maps';
$this->places = new Google_Service_Maps_Places_Resource(
$this,
$this->serviceName,
'places',
array(
'methods' => array(
'autocomplete' => array(
'path' => 'place/autocomplete/json',
'httpMethod' => 'GET',
'parameters' => array(
'input' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'sensor' => array(
'location' => 'query',
'type' => 'boolean',
'required' => true,
),
'location' => array(
'location' => 'query',
'type' => 'string',
),
'radius' => array(
'location' => 'query',
'type' => 'integer',
),
),
),
)
)
);
}
}
class Google_Service_Maps_Places_Resource extends Google_Service_Resource
{
public function autocomplete($input, $lat, $lng, $radius, $optParams = array())
{
$params = array('input' => $input, 'location' => "$lat,$lng", 'radius' => $radius, 'sensor' => false);
$params = array_merge($params, $optParams);
return $this->call('autocomplete', array($params));
}
}
API batch calling code:
<?php
const API_KEY = 'MY_API_KEY';
set_include_path("google-api-php-client/src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Maps.php';
require_once 'Google/Http/Batch.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey(API_KEY);
$client->setUseBatch(true);
$batch = new Google_Http_Batch($client);
$service = new Google_Service_Maps($client);
$inputs = array(
'Dolore',
'MacAl',
'App Aca'
);
foreach($inputs as $input) {
$req = $service->places->autocomplete($input, 37.7833, -122.4167, 500);
$batch->add($req, $input);
}
$results = $batch->execute();
print_r($results);
print_r($req);

how to load database content to dropdown options (select)

i'm still working on my own drupal 7 module, and i'm having some trouble. I'm trying to load database content to dropdown option (select), i have read and write the same code from drupal example, but my database still not loading, only empty option.
what i'm asking is there anything wrong on my code or is there any faster way to load database to dropdown option other than the drupal example???
here the code i'm working on
function prod_entry_load($entry = array()) {
$select = db_select('aa_1122','aa');
$select->fields('aa');
foreach ($entry as $field => $value) {
$select->condition($field, $value);
}
return $select->execute()->fetchAll();
}
function prod(){
return drupal_get_form('prod_form');
}
function prod_form($form_state){
$form = array(
'#prefix' => '<div id="updateform">',
'#suffix' => '</div>',
);
$entries = prod_entry_load();
$keyed_entries = array();
if (empty($entries)) {
$form['no_values'] = array(
'#value' => t("No entries exist in the table dbtng_example table."),
);
return $form;
}
foreach ($entries as $entry) {
$options[$entry->no] = t("#no: #name ", array('#no' => $entry->no, '#name' => $entry->name));
$keyed_entries[$entry->no] = $entry;
}
$default_entry = !empty($form_state['values']['no']) ? $keyed_entries[$form_state['values']['no']] : $entries[0];
$form_state['entries'] = $keyed_entries;
$form['no'] = array(
'#type' => 'select',
'#title' => t('Choose'),
'#default_value' => $default_entry->no,
'#ajax' => array(
'wrapper' => 'updateform',
'callback' => 'prod_form_update_callback',
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
'#ajax' => array(
'callback' => 'ajax_alert',
),
);
return $form;
}
function prod_form_update_callback($form, $form_state) {
$entry = $form_state['entries'][$form_state['values']['no']];
foreach (array('name') as $item) {
$form[$item]['#value'] = $entry->$item;
}
return $form;
}
You've just forgotten to add the #options key to your select element, the code should read like this:
$form['no'] = array(
'#type' => 'select',
'#title' => t('Choose'),
'#default_value' => $default_entry->no,
'#options' => $options, // This is the bit that was missing
'#ajax' => array(
'wrapper' => 'updateform',
'callback' => 'prod_form_update_callback',
),
);
You could shorten your query/options code slightly using a combination of string concatenation in MySQL and the db fetchAllKeyed() method:
$query = db_select('aa_1122', 'aa')->fields('aa', array('no'));
$query->addExpression("CONCAT(no, ': ', name)", 'display');
$options = $query->execute()->fetchAllKeyed();

Resources