is it possible to get post data/type from the wordpress rest api using url as parameter?
I knowing this function already from soundcloud. There is an resolve function with an url parameter (see https://developers.soundcloud.com/docs/api/reference#resolve). When you call this rest api endpoint, you get detailed information if the url is for example a track or playlist.
Unfortunately i couldn't find a function at the wordpress rest api documentation for doing this. What i exactly want is to get the post data/type by only knowing the url
https://demo.wp-api.org/2017/05/23/hello-world/ => post
https://demo.wp-api.org/example => page
https://demo.wp-api.org/category/example => category
With a function like this
https://demo.wp-api.org/wp-json/wp/v2/resolve?url=https://demo.wp-api.org/2017/05/23/hello-world/
Is there a way to do this? Or do i need to write my own rest api endpoint with a wordpress plugin?
this solved the problem
function route_handler($request)
{
global $wp;
global $wp_query;
$parameters = $request->get_json_params();
$url = $parameters["url"];
$_SERVER['REQUEST_URI'] = $url;
$wp->parse_request();
$wp->query_posts();
//Insert queries for more specific information
//Modify or simplify the query results
//Here I'm just returning the query results.
return json_encode($wp_query);
}
add_action('rest_api_init', function () {
register_rest_route('custom-theme/v1', '/route', array(
'methods' => 'POST',
'callback' => 'route_handler',
));
});
see: https://medium.com/#harryhorton/query-wp-rest-api-using-any-permalink-url-f5e4e4dd36b7
You could just get all the posts https://demo.wp-api.org/wp-json/wp/v2/posts and then do some thing like:
$.each(data, function(index, post){
if(post.link == yourUrl){
//yourcode
}
});
If you don't want to write your own endpoint
Related
Wordpress has an awesome REST API interface.
https://developer.wordpress.org/rest-api/reference/
But the content in wp_options table seems to be missing REST support. Is there a way to access the content in wp_otions table as REST endpoint via plugins?. Thanks.
There is the settings endpoint, but it only contains a surprisingly limited amount of them it seems.
This is something you could very easily do yourself though. I'm not sure if any plugins do it, but I also wouldn't recommend a plugin for something that can be done with less than 20 lines of code.
You just need to register a route using register_rest_route() on the rest_api_init hook, and pass it a callback function. You can drop code like this in your functions.php file or create a Must Use Plugin and drop the code in there, either way.
add_action( 'rest_api_init', function () {
register_rest_route( 'my-custom-route/v1', '/opt/', array(
'methods' => 'GET',
'callback' => 'get_rest_option',
//'permission_callback' => function () {
// return current_user_can( 'administrator' );
//}
) );
} );
function get_rest_option( $data ) {
return get_option( $data['option_name'] );
}
The above will give you access to whatever option you want by accessing:
/wp-json/my-custom-route/v1/opt/?option_name=siteurl
I went ahead and dropped an example on a site of mine:
https://xhynk.com/content-mask/wp-json/my-custom-route/v1/opt/?option_name=blogname
https://xhynk.com/content-mask/wp-json/my-custom-route/v1/opt/?option_name=siteurl
However, this will potentially expose anything in your options table. I went ahead and commented out the permission_callback so that any person, signed in or not, can access it. However, I also added a check like this:
function get_rest_option( $data ) {
if( $data['option_name'] === 'siteurl' || $data['option_name'] === 'blogname' ){
return get_option( $data['option_name'] );
} else {
return 'Unauthorized. Use `siteurl` or `blogname`';
}
}
You can see that home will fail: https://xhynk.com/content-mask/wp-json/my-custom-route/v1/opt/?option_name=home
I would recommend adding in a valid array of options, or using the permission_callback in order to lock it down a bit. You could even have an access key instead, and keep that key secret. Either way, be aware of the security implications of exposing your entire wp_options table, and take some sort of preventative measure!
I want to be able to add meta to a media post type by using WP REST API.
I want to use Postman because, for now, I just want to test how the API is working. The docs seems to be somewhat confusing. I would be grateful if you have any working examples.
Basically, I want to add copyright meta field to the media using this API.
for creating API you need to add route first. you can add route using below code:
function custom_meta_api() {
register_rest_route('wp/v1', '/update_meta/(?P<id>[\d]+)', array(
array(
'methods' => 'POST',
'callback' => 'saveMeta',
),
));
}|
add_action('rest_api_init', 'custom_meta_api');
you can pass your image id in (?P<id>[\d]+)
now in postman write url
http://your-url/wp-json/wp/v1/update_meta/5 with POST request
in body you can write below code
{"data":
{
"copyright":"xyz"
}
}
and to save in postmeta table create function saveMeta(which you have written in callback). Code for the function is below:
function saveMeta(WP_REST_Request $data) {
$bookingID = $data['id'];
$request = $data->get_json_params();
extract($request['data']);
update_post_meta($bookingID, 'copyright', $copyright);
$response = array();
$response["code"] = "success";
$response["message"] = "";
$response["data"] = array();
$response["data"][] = 'meta added';
return $response;
}
I have built a Wordpress plugin that among other things, creates several Woocommerce Webhooks upon activation. This is done using internal API classes and functions, as per below:
function createWebhook($userID,$topic,$secret,$deliveryURL,$status)
{
$webhook = new WC_Webhook();
$webhook->set_user_id($userID); // User ID used while generating the webhook payload.
$webhook->set_topic( $topic ); // Event used to trigger a webhook.
$webhook->set_secret( $secret ); // Secret to validate webhook when received.
$webhook->set_delivery_url( $deliveryURL ); // URL where webhook should be sent.
$webhook->set_status( $status ); // Webhook status.
$save = $webhook->save();
return $save;
}
This works well.
What I want to be able to do is remove these Webhooks upon deactivation of the plugin. Is there any way to fetch the Woocommerce Webhooks via the internal Wordpress or Woocommerce API, so I can loop through and remove the relevant ones?
I would just remove all Webhooks where the delivery URL has a domain of xyz.com. This part is straight-forward, I just don't know how to fetch the Webhooks.
I don't want to use the external Woocommerce API, which requires an API key and HTTP requests.
Thanks
I ended up querying the database to get the webhooks, which looks to be working well. I'm not sure there's any other way. Please let me know if there is!
global $wpdb;
$results = $wpdb->get_results( "SELECT webhook_id, delivery_url FROM {$wpdb->prefix}wc_webhooks" );
foreach($results as $result)
{
if(strpos($result->delivery_url, 'domain.com') !== false)
{
$wh = new WC_Webhook();
$wh->set_id($result->webhook_id);
$wh->delete();
}
}
#greg's answer points you in the right direction, but the returned data is just an array of ID's for each webhook, to get more data you need to parse those ID's into webhook objects - which has protected props, but public getter methods, like so:
$data_store = \WC_Data_Store::load( 'webhook' );
$webhooks = $data_store->search_webhooks([ 'status' => 'active', 'paginate' => true ] );
$_items = array_map( 'wc_get_webhook', $webhooks->webhooks );
$_array = [];
foreach( $_items as $_item ){
$_array[] = [
'id' => $_item->get_id(),
'name' => $_item->get_name(),
'topic' => $_item->get_topic(),
'delivery_url' => $_item->get_delivery_url(),
'secret' => $_item->get_secret(),
];
}
You can get an array of all webhook IDs with the following:
$data_store = WC_Data_Store::load( 'webhook' );
$webhooks = $data_store->search_webhooks();
That's what WooCommerce does when building the table list:
https://github.com/woocommerce/woocommerce/blob/master/includes/admin/class-wc-admin-webhooks-table-list.php
Here is the custom end points What i have created here for getting all themes. But in json it’s not returning result as expected.
add_action( ‘rest_api_init’, function () {
//Path to rest endpoint
register_rest_route( ‘theme/v1’, ‘/get_theme_list/’, array(
‘methods’ => ‘GET’,
‘callback’ => ‘theme_list_function’
) );
});
// Our function to get the themes
function theme_list_function(){
// Get a list of themes
$list = wp_get_themes();
// Return the value
return $list;
}
?>
If I can see simply the wp_get_themes() function it will return all the themes and its description in arrays. and It’s return fine in arrays but when i am encoding this into json to pass data its returning only array keys.
Producing only key name like in this way
All: {"basepress":{"update":false},"codilight-lite":{"update":false},"twentyfifteen":{"update":false},"twentyseventeen":{"update":false},"twentysixteen-child":{"update":false},"twentysixteen":{"update":false}}
I need all the information about the themes.
How can i do that with custom REST end points.
Please help.
Try this code
add_action( 'rest_api_init', function () {
//Path to rest endpoint
register_rest_route( 'theme/v1', '/get_theme_list/', array('methods' => 'GET','callback' => 'theme_list_function') );
});
// Our function to get the themes
function theme_list_function(){
// Get a list of themes
$list = wp_get_themes();
$varTheme = array();
foreach($list as $theme=>$value){
$varTheme[$theme] = (array)$value;
}
return $varTheme;
}
So I'm trying to work with the WP REST API. Using latest version of WP. I am using this in an external application and testing with Postman.
This is what I want to do:
display custom meta fields in the GET posts request
GET all posts (no limit)
create / update / delete (multiple) meta fields in one API request
Are these things possible with WP REST API? If so, can anyone share some examples?
I know all these work very well with WooCommerce REST API.
The better way is to use a custom endpoint to achieve this. You must create your own plugin for this...
//register different functions for different methods, use parameters in url for GET calls
register_rest_route('plugin_name', 'your_endpoint', array(
array('methods' => 'POST',
'callback' => 'magic_function',
))
);
function magic_function( $request ) {
//You can filter the query to get all posts (rest_{$this->post_type}_query)
add_filter('rest_post_query','my_custom_query', 10, 3);
$custom_request = new WP_REST_Request( 'GET', '/wp/v2/post');
$response= rest_do_request( $custom_request );
$response->data['meta_field'] = get_post_meta($response->data['id'], 'meta_field',true);
return new WP_REST_Response($response->data);
}
function my_custom_query($args, $request){
//returns all posts in request...
$args['numberposts'] = -1;
return $args;
}