PUT HTTP Request in HTTP API Wordpress - wordpress

I'm unable to use put http requests in WordPress.
https://codex.wordpress.org/HTTP_API
This link says you can do it through wp_remote_request()? But where to specify that ?
Can anyone help me with this? I need a code.

$body = array(
"status" => "publish"
);
$args = array(
'headers' => array(
'Content-Type' => 'application/json',
),
'body' => json_encode($body),
'method' => 'PUT'
);
$result = wp_remote_request( "http:300/wp-json/wp/post/1", $args );

Like this
$response = wp_remote_request( 'http://test.com/test', [
'method' => 'PUT'
] );

Related

Wordpress: Problem with rest_cookie_invalid_nonce

When I send rest request to the wp-rest by:
$response = wp_remote_post( $url, array(
'method' => 'POST',
// 'headers' => $headers,
'httpversion' => '1.0',
'sslverify' => false,
'body' => json_encode( array(
'data' => $field,
))
));
Unfortunately, I get 403 error:
{"code":"rest_cookie_invalid_nonce","message":"Kodem jednorazowy z ciasteczka jest nieprawid\u0142owy","data":{"status":403}}
Maybe someone knows how to resolve this issue?
When you use wp_remote_... your cookies are not included. WordPress REST API uses the _wpnonce value to validate your session against the wp_rest keyword and your cookie values. To fix this, your options are to either switch to an AJAX browser call to the endpoint from the same browsing session, or you can stick with the remote REST API request and include your cookies in it like this:
$cookies = [];
foreach( $_COOKIE as $name => $value ) {
$cookies[] = new WP_Http_Cookie(
[ 'name' => $name, 'value' => $value ]
);
}
$args = [
'body' => [],
'cookies' => $cookies,
'headers' => [ 'Content-type' => 'application/json' ],
];
$url = get_rest_url() . 'endpoint/v1/endpoint/';
$response = wp_remote_get( $url, $args );

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' );

Is there any way to get related posts API in 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.

Insert custom post type with Custom field by using wp rest api

Hello i am unable to store the value of author field by using wp rest api. author is a custom field in custom post type book.all other fields are stored correctly. it ignores all the custom field of custom post type book.
<?php
$curl = curl_init();
$data = array(
'title' => "book 1",
'status' => "publish",
'content' => "Inserting data through rest api ",
'format' => 'standard',
'author' => 'Jaipur',
);
curl_setopt_array($curl, array(
CURLOPT_URL => "http://localhost/wp-json/wp/v2/book/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_USERPWD => "admin" . ":" . "admin",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"Content-Type: application/x-www-form-urlencoded"
),
CURLOPT_POSTFIELDS => http_build_query($data),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
You need to mention The ID for the author of the object. Not the name or something.
https://developer.wordpress.org/rest-api/reference/posts/#create-a-post

wp_remote_post with file payload

I'm attempting to POST a file through wp_remote_post. Unfortunately, any file stream, or file paths (prepended with CURL style #, or not), passed to this function are simply dropped and removed from the payload.
I found a post on wp-hackers, however, it's extremely hack-ish and error prone. Is there really no way to transmit a file through this function without writing a complete HTTP payload from scratch?
Here's an example code block using CURL style (prepending path with #), if interested:
$body["attachment[{$i}]"] = "#{$attachment}";
$data = array(
'body' => $body,
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( "user:{$apiKey}" )));
$url = "https://api.someservice.net/{$domain}/endpoint";
$response = wp_remote_post( $url, $data );
Thanks!
Post data should be sent in the body as an array. Example passing post data:
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array( 'username' => 'bob', 'password' => '1234xyz' ),
'cookies' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}
In the example above, $response['body'] will contain the actual page content returned by the server.

Resources