Respond to custom URL in wordpress plugin - wordpress

So, I'm trying to write a wordpress plugin which acts like an API and responds to a specific HTTP request. I cache some data in my plugin and I would like to fetch the data in the other side using AJAX or sth.
What actions or filters should I use? I've tried using request filter but couldn't figure out how it works.

Use the WP REST API for this: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/
Below is a simple example of how to add a custom route and how to handle the request.
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/my-custom-route/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
function my_awesome_func( WP_REST_Request $request ) {
// You can access parameters via direct array access on the object:
$param = $request['some_param'];
// Or via the helper method:
$param = $request->get_param( 'some_param' );
// You can get the combined, merged set of parameters:
$parameters = $request->get_params();
// The individual sets of parameters are also available, if needed:
$parameters = $request->get_url_params();
$parameters = $request->get_query_params();
$parameters = $request->get_body_params();
$parameters = $request->get_json_params();
$parameters = $request->get_default_params();
// Uploads aren't merged in, but can be accessed separately:
$parameters = $request->get_file_params();
}

Related

How can I update Wordpress plugin with transient by add authorize_token to header

I am trying to update my WordPress plugins automatically using transient.
I have one that works but it adds authorize_token to query params like below code.
$new_files = $this->github_response['zipball_url']; // Get the ZIP
***$package = add_query_arg(array("access_token" => $this->authorize_token), $new_files);***
$slug = current( explode('/', $this->basename ) ); // Create valid slug
$plugin = array( // setup our plugin info
'url' => $this->plugin["PluginURI"],
'slug' => $slug,
'package' => $package,
'new_version' => $this->github_response['tag_name']
);
$transient->response[$this->basename] = (object) $plugin;
but i have received email from github that says i should add authorize_token to header.
I'm trying to find solution by google, but i can't find it.
How can I fix it?
I figured that you will have to add a filter to the http_request. So when wordpress will try any http request it will go through your filter. Then inside that filter you can check the url and if it is your plugin source url, you can then add your accessToken to the header.
this method was in my updater class, and I had setup the class property accessToken and username when initializing the updater.
add_filter( "http_request_args", array( $this, "addHeaders") , 10, 3);
public function addHeaders($parsed_args, $url)
{
if(empty($parsed_args['headers']))
{
$parsed_args['headers'] = [];
}
if(strpos($url, "https://api.github.com/repos/{$this->username}/{$this->repo}") !== FALSE)
{
$parsed_args['headers']['Authorization'] = "token $this->accessToken";
error_log("Adding token for : $url");
}
else
{
error_log("Not adding token for $url");
}
return $parsed_args;
}

Wordpress REST response shows taxonomy categories only with ID's

I'm using WP as a headless CMS with ACF en ACF-2-REST plugins. I've added categories to a post-type and when I make a GET call, it shows me all the information of a particular post including the categories, but only the ID's. If I want to match it, I have to do another call to Categories to get the information of that categories (name, parent etc).
How can I show that information instead of just the ID in a post call?
How the JSON looks now at the /activities call:
{
"id":111,
"date":"2020-01-18T15:39:27",
"date_gmt":"2020-01-18T15:39:27",
"guid":{"rendered":"https:\/\/url.be\/?post_type=activities&p=111"},
"modified":"2020-01-18T15:39:27",
"modified_gmt":"2020-01-18T15:39:27",
"slug":"walking-on-wood",
"status":"publish",
"type":"activities",
"link":"https:\/\/url.be\/activities\/walking-on-wood\/",
"title":{"rendered":"Walking on wood"},
"template":"",
"categories":[14,25,13,2,18,21,6,24],
"acf":{...}
}
What I want to show in the "categories" instead of just the numbers (from the categories call)
{
"id":3,
"count":1,
"description":"",
"link":"https:\/\/url.be\/category\/duration\/lower-than-30-min\/",
"name":"< 30 min.",
"slug":"lower-than-30-min",
"taxonomy":"category",
"parent":2,"meta":[],
"acf":[],
"_links":{"self":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/categories\/3"}],
"collection":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/categories"}],
"about":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/taxonomies\/category"}],
"up":[{"embeddable":true,"href":"https:\/\/url.be\/wp-json\/wp\/v2\/categories\/2"}],
"wp:post_type":[{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/posts?categories=3"},{"href":"https:\/\/url.be\/wp-json\/wp\/v2\/activities?categories=3"}],
"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}
}
Can't find any solution on the internet how I could manipulate the structure of that JSON with a custom function, would appreciate it a lot if someone point me to the right direction. Thanks!
As discussed in the comments section, a solution to this question is to use a custom endpoint method for the WP REST API and perform extra queries in there to get the data you need. This way, you can do all the data manipulation to get the perfect response, resulting in one REST call.
As taken from the official developer docs
Define an endpoint method and add some extra data
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func', //note that this is the method it will fire
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric( $param );
}
),
),
) );
/**
* Grab latest post by an author along with its category!
*
* #param array $data Options for the function.
* #return array Post,
*/
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if(!empty($posts)) {
//Example of appending extra data
foreach($posts as $post) {
$category = wp_get_post_terms($post->ID, 'category');
$post['category'] = $category;
}
return $posts;
} else {
return new WP_Error( 'no_author', 'Invalid author', array( 'status' => 404 ) );
}
}

update_callback not calling proper function when sending post

So, here's my code so far:
add_action( 'rest_api_init', 'rest_api_user_meta_fields' );
function rest_api_user_meta_fields() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'user', 'grad', array(
'get_callback' => 'get_user_acf_fields',
'update_callback' => 'update_user_acf_fields',
'schema' => null,
)
);
}
function get_user_acf_fields( $object ) {
//get the id of the post object array
$grad = get_field('grad', 'user_32');
error_log($object);
return $grad;
}
function update_user_acf_fields( $value, $object, $field_name ) {
error_log($value);
error_log($field_name);
error_log($object);
}
Now, I expect to have get_user_acf_fields function to be executed when I send GET request to /users/ endpoint, and update_user_acf_fields to be run when I send POST request to said endpoint. In both cases it executes former, get_user_acf_fields, function. What am I doing wrong here?
Maybe you didn't include the proper nonce?
For developers making manual Ajax requests, the nonce will need to be
passed with each request. The API uses nonces with the action set to
wp_rest. These can then be passed to the API via the _wpnonce data
parameter (either POST data or in the query for GET requests), or via
the X-WP-Nonce header. If no nonce is provided the API will set the
current user to 0, turning the request into an unauthenticated
request, even if you’re logged into WordPress.
— Read more on https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
Here's your code that I modified and tested working on WordPress 4.9.5 with Advanced Custom Fields 4.4.12.
add_action( 'rest_api_init', 'rest_api_user_meta_fields' );
function rest_api_user_meta_fields() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'user', 'grad', array(
'get_callback' => 'get_user_acf_fields',
'update_callback' => 'update_user_acf_fields',
'schema' => [
'description' => 'User grad blah',
'type' => 'string',
],
)
);
}
// $user_arr is an `array` of the user data; e.g. `id`, `username`, and `name`.
// $field_name is the name of the ACF custom field; i.e. in this case, it's `grad`.
function get_user_acf_fields( $user_arr, $field_name ) {
// Get the value of the 'grad' custom field.
$grad = get_field($field_name, 'user_' . $user_arr['id']);
error_log(var_export( $user_arr, true ));
error_log($field_name);
//return $grad;
return $field_name . ';' . $grad . ';' . $user_arr['id'];
}
// $field_value is the value of the ACF custom field; i.e. in this case, it's `grad`.
// $user_obj is an `object` of the user data; e.g. `id`, `username`, and `name`.
function update_user_acf_fields( $field_value, $user_obj, $field_name ) {
// Get the value of the 'grad' custom field.
$grad = get_field($field_name, 'user_' . $user_obj->ID);
if ( $grad !== $field_value ) {
update_field( $field_name, $field_value, 'user_' . $user_obj->ID );
}
error_log($field_value);
error_log($field_name);
error_log(var_export( $user_obj, true ));
return true;
}
And here's the HTML and JS/AJAX I used for testing the PHP code above.
$_GET, $_POST and UPDATE are different things to the rest API. Since update isn't necessarily a construct of the language it just means that when a request usually a $_POST comes in with a specific "Update" header that it should call your update function.

WordPress REST API not enabled on new account

Based on a quick research, WordPress REST API should be enabled after v4.7 (https://v2.wp-api.org/), however, I cannot access the REST API for my existing or new user by simply appending {name}.wordpress.com/wp-json, ie. https://steventsaotest.wordpress.com/wp-json does not return the expected JSON. Whereas sites like http://www.tribunemedia.com/wp-json works exactly as I wish, as well as my WordPress instance on Digital Ocean.
How can a user whose blog is registered with wordpress.com enable their REST API?
add_action( 'rest_api_init', function () {
$namespace = 'aroma_api';
register_rest_route( $namespace, '/get_signin', array (
'methods' => 'POST',
'callback' => 'get_singnin_data',
));
} );
function get_singnin_data($data)
{
global $wpdb;
$resultdata = array();
$resultdata['message'] = 'Login SuccessFull';
return $resultdata;
}

Custom wordpress REST API to accept JSON formatted input

I'm writing a wordpress REST API using the WP REST v2. Is there a way we can process the incoming JSON parameters (instead of query params) within the callback function, which we define in the register_rest_route function?
eg:
function wpplugin_register_routes() {
register_rest_route( 'testapi/v1', 'users', array(
'methods' => 'POST',
'callback' => 'wpplugin_process_json_params',
) );
}
function wpplugin_process_json_params( WP_REST_Request $request ) {
// Process the $request which should be a JSON string
}
Found the solution for this. WP_REST_Request object contains the JSON parameters so can retrieve it using $request['parameter_name'] same as the GET / POST parameters.

Resources