wp_schedule_event does not call function associated to it - wordpress

I am trying to schedule an event on hourly basis, that should store some data to a mlab database(mongo db), but the function is not getting called.
class plug_Activator{
public function __construct() {
add_action( 'my_hourly_event', 'tmpp' );
}
function activate() {
if ( ! wp_next_scheduled( 'tmpp' ) ) {
wp_schedule_event( time() - 3540, 'hourly', 'my_hourly_event');
}
}
function tmpp(){
$args= array(
"website"=> "www.xyz.com",
"post"=> "wasupp"
);
$response = wp_remote_post( 'https://api.mlab.com/api/1/databases/todo/collections/todos?apiKey=xxxx', array(
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'body' => json_encode($args),
'method' => 'POST'
));
}}

Related

WordPress REST API Custom Endpoint with URL Parameter

I am trying to create a custom endpoint for the WordPress REST API and pass parameters through the URL.
The endpoint currently is:
/wp-json/v1/products/81838240219
What I am trying to achieve is an endpoint that looks like this and being able to retrieve the identifier parameter in the callback.
/wp-json/v1/products?identifier=81838240219
// Custom api endpoint test
function my_awesome_func( $data ) {
$identifier = get_query_var( 'identifier' );
return $identifier;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'api/v1', '/products=(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
First you need to pass in the namespace to register_rest_route
Like this
add_action( 'rest_api_init', function () {
register_rest_route( 'namespace/v1', '/product/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
Your name space namespace/v1 and your route is /product/{id} like this
/namespace/v1/product/81838240219
and now you can use the route inside your function like this
function my_awesome_func( $data ) {
$product_ID = $data['id'];
}
If you need to add options for ex.
/namespace/v1/product/81838240219?name=Rob
and use it inside the function like this
function my_awesome_func( $data ) {
$product_ID = $data['id'];
$name = $data->get_param( 'name' );
}
The process is very simple but requires you to read this documentation
I modified the provided answer a little to get my desired endpoint:
/wp-json/api/v1/product?identifier=81838240219
add_action( 'rest_api_init', function () {
register_rest_route( 'api/v1', '/product/', array(
'methods' => 'GET',
'callback' => 'ea_get_product_data',
) );
} );
function ea_get_product_data( $data ) {
$identifier = $data->get_param( 'identifier' );
return $identifier;
}
If you want to pass alphanumeric parameters, use [a-zA-Z0-9-] instead of \d
add_action( 'rest_api_init', function () {
register_rest_route( 'namespace/v1', '/product/(?P<id>[a-zA-Z0-9-]+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );

REST filter based on ACF properties does not work

I have this REST data:
[{"id":215,"acf":{"stad":{"value":"barcelona","label":"barcelona"},"description":"","images":[{"ID":191,"id":191,"title":"logo-black.png","filename":"logo-black.png","filesize":3080,"url":"https:\/\/wordpress-132670-574369.cloudwaysapps.com\/wp-content\/uploads\/logo-black.png","link":"https:\/\/wordpress-132670-574369.cloudwaysapps.com\/logo-black-png\/","alt":"","author":"1","description":"","caption":"","name":"logo-black-png","status":"inherit","uploaded_to":0,"date":"2018-04-16 15:39:37","modified":"2018-08-05 15:19:12","menu_order":0,"mime_type":"image\/png","type":"image","subtype":"png","icon":"https:\/\/wordpress-132670-574369.cloudwaysapps.com\/wp-includes\/images\/media\/default.png","width":443,"height":98,"sizes":{"thumbnail":"https:\/\/wordpress-132670-574369.cloudwaysapps.com\/wp-content\/uploads\/logo-black-150x98.png","thumbnail-width":150,"thumbnail-height":98,"medium":"https:\/\/wordpress-132670-574369.cloudwaysapps.com\/wp-content\/uploads\/logo-black-300x66.png","medium-width":300,"medium-height":66,"medium_large":"https:\/\/wordpress-132670-574369.cloudwaysapps.com\/wp-content\/uploads\/logo-black.png","medium_large-width":443,"medium_large-height":98,"large":"https:\/\/wordpress-132670-574369.cloudwaysapps.com\/wp-content\/uploads\/logo-black.png","large-width":443,"large-height":98}}]}},{"id":205,"acf":{"stad":{"value":"oslo","label":"oslo"},"description":"","images":false,"myid":"333"}}]
I created a filter to query with the "myid" parameter like this:
/wp-json/wp/v2/hotels/?myid=333
This is the filter code I added to the functions.php:
add_filter('rest_hotels_vars', function ($valid_vars)
{
return array_merge($valid_vars, array('myid', 'meta_query'));
});
add_filter('rest_hotels_query', function($args, $request)
{
$myid = $request->get_param('myid');
if (!empty( $myid))
{
$args['meta_query'] = array(
array(
'key' => 'myid',
'value' => $myid,
'compare' => '=',
)
);
}
return $args;
}, 10, 2 );
Hotels is a custom post type.
The query always returns all the rows, the filter has no effect.
What's wrong here?
If you look into the filter closely you will understand the error.
apply_filters( "rest_{$this->post_type}_query", array $args, WP_REST_Request $request );
This is your code:
add_filter('rest_hotels_query', function($args, $request){
$myid = $request->get_param('myid');
if (!empty( $myid))
{
$args['meta_query'] = array(
array(
'key' => 'myid',
'value' => $myid,
'compare' => '=',
)
);
}
return $args;
}, 10, 2 );
Here rest_hotels_query : we need to put post type name please be careful, if your post type name is hotel then filter should be like : "rest_hotel_query"
This is the working code:
add_filter('rest_hotel_query', function($args, $request){
$myid = $request->get_param('myid');
if (!empty( $myid))
{
$args['meta_query'] = array(
array(
'key' => 'myid',
'value' => $myid,
'compare' => '=',
)
);
}
return $args;
}, 10, 2 );
Same case with the collection parameters for the posts controller:
apply_filters( "rest_{$this->post_type}_query", array $args, WP_REST_Request $request );
It should be :
add_filter('rest_hotel_collection_params', function ($valid_vars){
return array_merge($valid_vars, array('myid', 'meta_query'));
});
The rest_query_vars filter no longer exists. Take a look at https://developer.wordpress.org/reference/hooks/rest_this-post_type_collection_params/ and https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/
So replace this
add_filter('rest_hotels_vars', function ($valid_vars)
{
return array_merge($valid_vars, array('myid', 'meta_query'));
});
with this
add_filter('rest_hotels_collection_params', function ($valid_vars)
{
return array_merge($valid_vars, array('myid', 'meta_query'));
});
and it should work.

Wordpress REST API create custom GET endpoint from custom table

I'm trying to get some data from a custom database table. But I get a rest forbidden error.
add_action( 'rest_api_init', function () {
register_rest_route( 'emevents/v1', '/all', array(
'methods' => 'GET',
'callback' => 'handle_get_all',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
} );
function handle_get_all( $data ) {
global $wpdb;
$query = "SELECT event_name FROM 'wp_em_events'";
$list = $wpdb->get_results($query);
return $list;
}

wp_get_current_user() function not working in Rest API callback function

Please consider the following php class extends the WP_REST_Controller class of Wordpress related to Rest API:
<?php
class MCQAcademy_Endpoint extends WP_REST_Controller {
/**
* Register the routes for the objects of the controller.
*/
public function register_routes() {
$version = '1';
$namespace = 'custompath/v' . $version;
$base = 'endpointbase';
register_rest_route(
$namespace,
'/' . $base,
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => array(),
)
)
);
}
/**
*
*/
public function get_items( $request ) {
$rs = array(
'data' => array(),
'request' => array(
'lang' => 'en',
),
);
$args = array();
$items = get_posts( $args );
foreach( $items as $item ) {
$itemdata = $this->prepare_item_for_response( $item, $request );
$rs['data'][] = $this->prepare_response_for_collection( $itemdata );
}
$rs['wp_get_current_user'] = wp_get_current_user(); // Does not output as expected
return new WP_REST_Response( $rs, 200 );
}
/**
* Check if a given request has access to get items
*/
public function get_items_permissions_check( $request ) {
return true; // to make readable by all
}
/**
* Prepare the item for create or update operation
*/
protected function prepare_item_for_database( $request ) {
return $request;
}
/**
* Prepare the item for the REST response
*/
public function prepare_item_for_response( $item, $request ) {
$data = array(
'ID' => $item->ID,
'post_content' => wpautop($item->post_content),
'post_title' => $item->post_title,
);
return $data;
}
/**
* Get the query params for collections
*/
public function get_collection_params() {
return array(
'page' => array(
'description' => 'Current page of the collection.',
'type' => 'integer',
'default' => 1,
'sanitize_callback' => 'absint',
),
'per_page' => array(
'description' => 'Maximum number of items to be returned in result set.',
'type' => 'integer',
'default' => 10,
'sanitize_callback' => 'absint',
),
'search' => array(
'description' => 'Limit results to those matching a string.',
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
),
);
}
// Register our REST Server
public function hook_rest_server(){
add_action( 'rest_api_init', array( $this, 'register_routes' ) );
}
}
$myEndpoint = new MCQAcademy_Endpoint();
$myEndpoint->hook_rest_server();
Everything is going well except calling the wp_get_current_user() function in the get_items() function return empty user even though the user is loggedin in the website.
What is the solution to get the loggedin user info in Rest API endpoint function?

How to hit the url in WordPress rest_api_init

I have set up the API end points in WordPress in theme functions.php.
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric( $param );
}
),
),
));
});
And the callback function is like:
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );
}
return $posts[0]->post_title;
}
I want to know what will be the url for this API and how can I hit that url?
Please help me out. I know this is simple thing but couldn't figure it out.

Resources