WP REST API v2 Can't use filters - wordpress

I Connecting with woocommerse with Oauth2.
But i can't use filters, example /wp-json/wp/v2/post&filter[category_name]=food
I get information about users, example http://my-site/wp-json/wp/v2/users, but on page i get info about first 10 users, i need more... When i use filter, example : http://my-site/wp-json/wp/v2/users?filter[posts_per_page]=5- filter not work
my code:
require('vendor/autoload.php');
const CLIENT_ID = 'my-ID';
const CLIENT_SECRET = 'my-secret';
const REDIRECT_URI = 'http://wooc/test.php';
const AUTHORIZATION_ENDPOINT = 'http://my-site/oauth/authorize';
const TOKEN_ENDPOINT = 'http://my-site/oauth/token';
$client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET);
if (!isset($_GET['code']))
{
$auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
header('Location: ' . $auth_url);
die('Redirect');
}
else
{
$params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI);
$response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code',$params);
}
$client->setAccessToken("a6kpdxqqs3runou66ovzjjy54rvfubv64hhpdomn");
$data = $client->fetch("http://my-site/wp-json/wp/v2/users?filter[posts_per_page]=5");
echo "<pre>";
var_dump($data);
I do not understand where the error!
Please help. thank you

The API response filtering functionality has been superseded by more robust query parameters like ?categories=, ?slug= and ?per_page=.

In WordPress 4.7 the filter argument for any post endpoint was removed, The filter argument allows the posts to be filtered using WP_Query public query vars. This plugin restores the filter parameter for sites that were previously using it: https://github.com/luisfredgs/rest-filter
However, you can also convert your existing code to remove filter.
Something along the lines of this:
http://my-site/wp-json/wp/v2/users?filter[posts_per_page]=5
becomes this:
http://my-site/wp-json/wp/v2/users?posts_per_page=5

Related

How to add meta fields to media using Wordpress REST API v2 by using Postman?

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;
}

Get list of Webhooks from Woocommerce

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

WP REST API - Issues

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;
}

How to sort customer list by using bigcommerce v2 api

How to sort customer list by using bigcommerce v2 api. I made below code.
$filter = array("page" =>$page, "limit" =>50);
$customersList = $this->store->getCustomers($filter); public static function getCustomers($filter = array())
{
$filter = Filter::create($filter);
return self::getCollection('/customers'. $filter->toQuery(), 'Customer');
}
First, I want sort first whole list by date_created in desc and then filter it for pagination . To show newly added record first.
Please help me to find out solution..
There isn't a supported sort from the API, so you'll have to sort the array. Laravel supports array_sort.
$customers = array_values(array_sort($array, function($value)
{
return $value['date_created'];
}));
https://laravel.com/docs/4.2/helpers#arrays

Module field with feeds, module generating data

I have an issue with triming a field before it is saved. I wanted to use substr(), or regex() with preg_match(). I have built a Drupal 7 module, but it can't work at all. I have tried using the trim plugin in feeds tamper module, but it doesn't seem to work. The data I am using is from a feed from Google Alerts. I have posted this issue here.
This is what I have done so far, and I know my regular expression is wrong; I was trying to get it do anything, just to see if I could get it to work, but I am pretty lost on how to add this type of function to a Drupal module.
function sub_node_save() {
$url = $node->field_web_screenhot['und'][0]['url'];
$url = preg_match('~^(http|ftp)(s)?\:\/\/((([a-z0-9\-]*)(\.))+[a-z0-9]*)($|/.*$)~i',$url );
$node->field_web_screenhot['und'][0]['url'] =$url;
return ;
}
I used the Devel module to get the field.
If there's an easy way to use substr(), I would consider that or something else.
Basically, I just want to take the Google redirect off the URL, so it is just the basic URL to the web site.
Depending on your question and later comments, I'd suggesting using node_presave hook (http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_presave/7) for this.
It's called before both insert (new) and update ops so you will need extra validations to prevent it from executing on node updates if you want.
<?php
function MYMODULE_node_presave($node) {
// check if nodetype is "mytype"
if ($node->type == 'mytype'){
// PHP's parse_url to get params set to an array.
$parts = parse_url($node->field_web_screenhot['und'][0]['url']);
// Now we explode the params by "&" to get the URL.
$queryParts = explode('&', $parts['query']);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
//valid_url validates the URL (duh!), urldecode() makes the URL an actual one with fixing "//" in http, q is from the URL you provided.
if (valid_url(urldecode($parms['q']))){
$node->field_web_screenhot['und'][0]['url'] = urldecode($parms['q']);
}
}
}

Resources