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.
Related
I am researching more and use the code..
I have done this code.
if (!defined('ABSPATH')) {
die;
}
if(!class_exists('ArtistPublic')):
class ArtistPublic
{
public static function createTemplate( ) {
global $user_ID;
$new_post = array(
'post_title' => 'Artist',
'post_content' => 'hello Artist',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'page',
);
$post_id = wp_insert_post($new_post);
if( !$post_id )
wp_die('Error creating template page');
else
update_post_meta( $post_id, '_wp_page_template', 'artist.php' );
// Filter page template
// add_filter('page_template', 'catch_plugin_template');
}
// Page template filter callback
public static function catch_plugin_template($template) {
if( is_page_template('artist.php') )
$template = WP_PLUGIN_DIR . '/ItgArtist/public/templates/artist.php';
return $template;
}
}
endif;
but create multiple page after refresh.
Is there any good way to create the page like as woocommerce does??
So code be like something
if (!defined('ABSPATH')) {
die;
}
if(!class_exists('ArtistPublic')):
class ArtistPublic {
public static function createTemplate( ) {
if( get_option('artist_page_id') ) :
global $user_ID;
$new_post = array(
'post_title' => 'Artist',
'post_content' => 'hello Artist',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'page',
);
$post_id = wp_insert_post($new_post);
if( !$post_id ) :
wp_die('Error creating template page');
else :
update_option('artist_page_id', $post_id);
update_post_meta( $post_id, '_wp_page_template', 'artist.php' );
endif;
endif;
// Filter page template
// add_filter('page_template', 'catch_plugin_template');
}
// Page template filter callback
public static function catch_plugin_template($template) {
if( is_page_template('artist.php') )
$template = WP_PLUGIN_DIR . '/ItgArtist/public/templates/artist.php';
return $template;
}
}
endif;
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.
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?
{"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.
Below is the code I am using
add_action( 'rest_api_init', 'add_custom_users_api');
function add_custom_users_api(){
register_rest_route( 'testing', '/users', array(
'methods' => 'GET',
'callback' => 'get_custom_users_data',
));
}
function get_custom_users_data($data){
//get users by market
$result = "Testing this";
return $result;
}
Below is the response I am getting
Try This
add_action( 'rest_api_init', 'add_custom_users_api');
function add_custom_users_api(){
register_rest_route( 'testing', '/users', array(
'methods' => 'GET',
'callback' => 'get_custom_users_data',
));
}
function get_custom_users_data($data){
//get users by market
$result = "Testing this";
return $result;
}
http://localhost/wordpress/wp-json/testing/users