Is there any way to get related posts API in WordPress? - wordpress

I need to create an API that will render a related post by category filter. I have written the code in my functions.php file but I did not get how can I pass a post id to the arguments?
function related_posts_endpoint( $request_data ) {
$uposts = get_posts(
array(
'post_type' => 'post',
'category__in' => wp_get_post_categories(183),
'posts_per_page' => 5,
'post__not_in' => array(183),
) );
return $uposts;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'sections/v1', '/post/related/', array(
'methods' => 'GET',
'callback' => 'related_posts_endpoint'
) );
} );
I need to pass the id from my current API call. So, I need to pass that id to the related API arguments that I have currently passed as static (180)
Image of Current post API from which I need to render a related API

You can add to your rest route a parameter called post_id, and then access the id from the request_data array.
function related_posts_endpoint( $request_data ) {
$post_id = $request_data['post_id'];
$uposts = get_posts(
array(
'post_type' => 'post',
'category__in' => wp_get_post_categories($post_id),
'posts_per_page' => 5,
'post__not_in' => array($post_id),
)
);
return $uposts;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'sections/v1', '/post/related/(?P<post_id>[\d]+)', array(
'methods' => 'GET',
'callback' => 'related_posts_endpoint'
));
});
You can add the id to the end of your URL call /post/related/183.

Your can get the post id like normal get request. ?key=value and use its ad $request['key'] so Your code should be like this.
function related_posts_endpoint( $request_data ) {
$uposts = get_posts(
array(
'post_type' => 'post',
'category__in' => wp_get_post_categories(183),
'posts_per_page' => 5,
'post__not_in' => array($request_data['post_id']),//your requested post id
)
);
return $uposts;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'sections/v1', '/post/related/', array(
'methods' => 'GET',
'callback' => 'related_posts_endpoint'
));
});
Now your api url should be like this /post/related?post_id=183
try this then let me know the result.

Related

How to access ACF field in a custom Wordpress Rest API endpoint?

I have a Advanced Custom Fields FAQ repeater field that I'm trying to add FAQ's to my custom search results, and am unable to get the field through the Rest API.
I'm registering the endpoint like so:
add_action('rest_api_init', 'register_search');
function register_search() {
register_rest_route('fralin/v1', 'search', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'search_results',
'permission_callback' => '__return_true',
));
}
Which calls the Callback:
function search_results($data) {
$main_query = new WP_Query(array(
'post_type' => array('product', 'post', 'page', 'diagram'), //Would grab FAQ as a custom post type, but it's not it's own custom post type - just custom fields on a page.
'posts_per_page' => 18,
'post_status' => 'publish',
'order_by' => 'relevance',
'order' => 'ASC',
'no_found_rows' => true,
's' => sanitize_text_field($data['term']),
));
$results = array(
'products' => array(),
'pages' => array(),
'posts' => array(),
'diagrams' => array()
);
while ($main_query->have_posts()) {
$main_query->the_post();
global $product;
global $post;
if (get_post_type() == 'product') {
array_push($results['products'], array(
'title' => $product->get_name(),
'link' => get_the_permalink(),
'featuredImage' => get_the_post_thumbnail_url(),
'sku' => $product->get_sku(),
'priceHTML' => $product->get_price_html(),
'tagline' => get_field('product_tagline', get_the_ID()),
'originalDesign' => get_field('original_design', get_the_ID()),
'productAttributes' => array(
get_field('pickup_design', get_the_ID()),
get_field('pickup_appearance', get_the_ID()),
),
));
}
if (get_post_type() == 'post') {
array_push($results['posts'], array(
'title' => get_the_title(),
'link' => get_the_permalink(),
'featuredImage' => get_the_post_thumbnail_url($post->ID, 'thumbnail'),
'publishedDate' => get_the_time('F j, Y'),
));
}
if (get_post_type() == 'page') {
array_push($results['pages'], array(
'title' => get_the_title(),
'link' => get_the_permalink(),
'faq' => get_field('faqs'), // Trying to access FAQ Questions and Answers here.
));
}
if (get_post_type() == 'diagram') {
array_push($results['diagrams'], array(
'title' => get_the_title(),
'thumbnail' => get_field('wiring_diagram_thumbnail')['sizes']['thumbnail'],
'pdf' => get_field('wiring_diagram_pdf'),
'description' => get_field('wiring_diagram_description')
));
}
}
return $results;
}
I see why I'm unable to get access to the FAQ value. It's searching the pages post type for any values search values, and none are there. FAQ's are just added to a page template - not it's own custom post type.
That said, I'm totally lost on how to include ACF fields in search results.
I want a user to search for "ice cream" and have my search function look for FAQ fields involving those keywords, and be able to return the question and answer in the search results. I'm just stuck at actually getting the values.
Any ideas on where to start? Thank you.

Passing shortcode attributes to WordPress Remote Post URL

I'm trying to pass shortcode attribute values directly into my url for a WordPress Remote Post request. Below is my code example below. I am using the following shortcode in my wordpress page
[example-data start="1" count="10"]
but i cannot get the start or the count data to work in the URL. Any help would be appreciated.
function display_example_data( $atts ) {
$value = shortcode_atts( array(
'start' => 1,
'count' => 10,
), $atts );
$url ="https://example.com/api/reviews?token=".$api_text_key."&start=".$value['start']."&count=".$value['count']."";
$response = wp_remote_post( $url, array(
'method' => 'GET',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'cookies' => array()
)
);
<?php }
add_shortcode( 'example-data', 'display_example_data' );

WP pagination in rest api

we have made a custom api to get all the post in descending order and we want to add pagination in that api, I have read other questions and answers also but didnt get any idea so can some one explain me with a simple code with pagination so that I can understand how it works.
This is my code so how can I add pagination can anyone explain to me because I searched other questaion also but I didnt get any idea.
define('API_ENDPOINT_VERSION',1);
//flush the rewrite rules on plugin activation
function apiendpoint_activate()
{
flush_rewrite_rules();
}
register_activation_hook(__FILE__,'apiendpoint_activate');
function apiendpoint_register_endpoints(){
register_rest_route(
'api/v1',
'/post',
[
'methods' => 'GET',
'callback' =>'api_get_post',
]
);
}
add_action('rest_api_init','apiendpoint_register_endpoints');
function api_get_post($request){
$ar = array( 'post_type'=>'post',
'posts_per_page'=>15,
'orderby' => 'date',
'order' => 'DESC',
);
$posts = get_posts($ar);
//var_dump($posts);
//exit;
$a = array();
if($posts){
foreach ($posts as $post) {
$a[]= array(
'title'=>$post->post_title,
'link'=>get_the_permalink($post->ID),
'category'=>get_the_category($post->ID),
'published_date'=>get_the_date('l, F j, Y',$post->ID),
'guid'=>$post->guid,
'image'=>get_the_post_thumbnail_url($post->ID,'large'),
'description'=>$post->post_excerpt,
'source'=>"Nepaljapan"
//'img'=>$img
);
}
return $a;
}
}
Try the below code:
define('API_ENDPOINT_VERSION', 1);
//flush the rewrite rules on plugin activation
function apiendpoint_activate() {
flush_rewrite_rules(); } register_activation_hook(__FILE__, 'apiendpoint_activate');
function apiendpoint_register_endpoints() {
register_rest_route(
'api/v1',
'/post',
[
'methods' => 'GET',
'callback' => 'api_get_post',
]
);
} add_action('rest_api_init', 'apiendpoint_register_endpoints');
function api_get_post($request) {
$ar = array('post_type' => 'posts',
'posts_per_page' => 15,
'orderby' => 'date',
'order' => 'DESC',
'paged' => ($_REQUEST['paged'] ? $_REQUEST['paged'] : 1)
);
$posts = get_posts($ar); //var_dump($posts); //exit; $a = array();
if ($posts) {
foreach($posts as $post) {
$a[] = array(
'title' => $post -> post_title,
'link' => get_the_permalink($post -> ID),
'category' => get_the_category($post -> ID),
'published_date' => get_the_date('l, F j, Y', $post -> ID),
'guid' => $post -> guid,
'image' => get_the_post_thumbnail_url($post -> ID, 'large'),
'description' => $post -> post_excerpt,
'source' => "Nepaljapan"
//'img'=>$img
);
}
return $a; }
}
Call API call as below:
/wp-json/api/v1/post?paged=1
Increase the paged value by 1 to get next paging posts.
Hope this helps!

Access to all content with specific post type (Wordpress)

I had a question about Wordpress + rest api,
I use register_rest_route for adding new end-point for my collection, and I also created a plugin named as 'article', and the type of this post type also is 'article'.
Now I wanna access all these post types in my new end-point with GET like this :
function my_awesome_func( $post_id ) {
$x = get_post_type_object( 'article' );
return $x[$post_id];
}
add_action( 'rest_api_init', function () {
register_rest_route( 'Articles/v2', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
I know you can't write $x[$post_id]. I wrote it to say that I wanna access to specific article id. what should I do?
thanks.
I solve this problem finally, I post it, it may be useful for others.
add_action( 'rest_api_init', function () {
register_rest_route( 'wp/v2/Articles', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
function my_awesome_func( $data ) {
$args = array(
'post_type' => 'article',
'p' => $data['id'],
);
$query = new WP_Query( $args );
return $query->post;
}

How do I get WordPress' REST API to include user metadata?

I've set up a WordPress site and added a couple of users. When I look directly in the wp_usermeta table in the database, there are several records there, so the users do also have some metadata.
According to the documentation, meta should be included when requesting users, but when I request /wp-json/wp/v2/users all the meta fields are an empty array.
What am I missing? How can I get metadata about users through the REST API?
I managed to find an even easier way to accomplish this, based on this part of the docs.
Not sure where it's best practice to put this code. Since I already have an API-related plugin, I just added the code there.
// legend: <type>, <meta_key>, <config>
register_meta('user', 'nickname', array(
"type" => "string",
"show_in_rest" => true // this is the key part
));
Now I just have to figure out which specific keys I need :)
This is not mine, founded at:
https://wordpress.stackexchange.com/questions/270154/getting-user-meta-data-from-wp-rest-api
Wrote here for future reference into StackOverflow:
Look into register_rest_field() to register meta with the rest api.
add_action( 'rest_api_init', 'adding_user_meta_rest' );
function adding_user_meta_rest() {
register_rest_field( 'user',
'collapsed_widgets',
array(
'get_callback' => 'user_meta_callback',
'update_callback' => null,
'schema' => null,
)
);
}
And then put your get_user_meta bit in the callback.
function user_meta_callback( $user, $field_name, $request) {
return get_user_meta( $user[ 'id' ], $field_name, true );
}
The WP_REST_Meta_Fields class may provide more useful insight as well.
Update: on registering custom routes
A quick and dirty partial example. Cobbled out of some stuff sitting in front of me, but it is not a working example.
May help as you read through docs. Follow the connection between the first register_rest_route, it's GET method's callback, my_get_callback, below, and the callback method's use of the WP_Rest_Request class. It should help to draw a connection of the steps. The docs I mentioned in the comments will get into other args, params, etc., and of course the permissions_callback stuff.
Hope it helps.
class My_Extend_Rest extends WP_REST_Controller {
public function __construct() {
add_action( 'rest_api_init', array( $this, 'register_routes' ) );
}//end __construct
public function register_routes() {
$version = '1';
$namespace = 'my-fancy-namespace/v' . $version;
$base = 'my-route-base';
// so, site.com/wp-json/my-fancy-namespace/v2/my-route-base/
register_rest_route( $namespace, '/'. $base, array(
array(
'methods' => 'GET',
'callback' => array( $this, 'my_get_callback' ),
'permission_callback' => array( $this, 'key_permissions_check' ),
),
array(
'methods' => 'POST',
'callback' => array( $this, 'my_post_callback' ),
'permission_callback' => array( $this, 'key_permissions_check' ),
),)
);
$base2 = 'my-second-base';
// so, site.com/wp-json/my-fancy-namespace/v2/my-second-base/
register_rest_route( $namespace, '/'. $base2, array(
array(
'methods' => 'GET',
'callback' => array( $this, 'my_get_callback_two' ),
'permission_callback' => array( $this, 'key_permissions_check' ),
),
array(
'methods' => 'POST',
'callback' => array( $this, 'my_post_callback_two' ),
'permission_callback' => array( $this, 'key_permissions_check' ),
),)
);
}//register_routes
public function key_permissions_check() {
//do permissions check stuff
}
public function my_get_callback( WP_REST_Request $request ) {
//do stuff with $request
//see the methods mentioned in the comment
}//end
}//end class

Resources