Wp Rest Api Custom End point POST request - wordpress

Im trying to post some data to custom api endpoint that i created,
This is what my wordpress custom endpoint code.
register_rest_route( 'api/v1', '/cities', array(
'methods' => 'POST',
'callback' => 'create_city_from_data'
));
And for testing I am trying to return the request like this
function create_city_from_data($req) {
return ['req' => $req];
}
but always i receive empty object as response, whatever i send in payload i didn't receive anything.
My payload is something like this
{ name: 'Hello', population: 565656 }
This is what is received from the request
{"req":{}}

By using below code you can view your payload.
add_action('rest_api_init', function () {
register_rest_route( 'api/v1', '/cities', array(
'methods' => 'POST',
'callback' => 'create_city_from_data'
));
});
function create_city_from_data($req) {
$response['name'] = $req['name'];
$response['population'] = $req['population'];
$res = new WP_REST_Response($response);
$res->set_status(200);
return ['req' => $res];
}
I have used postman to view the POST parameter

By using this function you can see all post of your custom post type in API...
Get All Post in your API Viewer.
Writer URL on your API viewer (e.g. I used Postman json api view, google chrome adon)
Domain-name/wp-json/showFavorites/v2?post_type=hotel
Here 'hotel' is the custom posttype.
Add this function in your functions.php
add_action( 'rest_api_init', 'wp_api_show_favorites_endpoints' );
function wp_api_show_favorites_endpoints() {
register_rest_route( 'showFavorites', '/v2', array(
'methods' => 'GET',
'callback' => 'showFavorites_callback',
));
}
function showFavorites_callback( $request_data ) {
global $wpdb;
$data = array();
$table = 'wp_posts';
$parameters = $request_data->get_params();
$post_type = $parameters['post_type'];
if($post_type!=''){
$re_query = "SELECT * FROM $table where post_type='$post_type'";
$pre_results = $wpdb->get_results($re_query,ARRAY_A);
return $pre_results;
}else{
$data['status']=' false ';
return $data;
}
}
And using this you can post your content from API
// POST All Posts using API
add_action( 'rest_api_init', 'wp_api_add_posts_endpoints' );
function wp_api_add_posts_endpoints() {
register_rest_route( 'addPost', '/v2', array(
'methods' => 'POST',
'callback' => 'addPosts_callback',
));
}
function addPosts_callback( $request_data ) {
global $wpdb;
$data = array();
$table = 'wp_posts';
// Fetching values from API
$parameters = $request_data->get_params();
$user_id = $parameters['user_id'];
$post_type = $parameters['post_type'];
$post_title = $parameters['post_title'];
$the_content = $parameters['the_content'];
$cats = $parameters['cats'];
$the_excerpt = $parameters['the_excerpt'];
$feature_img = $parameters['featured_image'];
// custom meta values
$contact_no = $parameters['contact_no'];
$email = $parameters['email'];
$hotel_url = $parameters['hotel_url'];
if($post_type!='' && $post_title!=''){
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags( $post_title),
'post_content' => $the_content,
'post_author' => '',
'post_excerpt' => $the_excerpt,
'post_status' => 'publish',
'post_type' => $post_type,
);
$new_post_id = wp_insert_post( $my_post );
function wp_api_encode_acf($data,$post,$context){
$customMeta = (array) get_fields($post['ID']);
$data['meta'] = array_merge($data['meta'], $customMeta );
return $data;
}
if( function_exists('get_fields') ){
add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3);
}
// Set post categories
$catss = explode(',', $cats);
if (!empty($catss)) {
if ($post_type == 'post') {
wp_set_object_terms( $new_post_id, $catss, 'category', false );
}
else{
wp_set_object_terms( $new_post_id, $catss, 'Categories', false ); // Executes if posttype is other
}
}
// Set Custom Metabox
if ($post_type != 'post') {
update_post_meta($new_post_id, 'contact-no', $contact_no);
update_post_meta($new_post_id, 'email', $email);
update_post_meta($new_post_id, 'hotel-url', $hotel_url);
}
// Set featured Image
$url = $feature_img;
$path = parse_url($url, PHP_URL_PATH);
$filename = basename($path);
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($feature_img);
$savefile = fopen($uploadfile, 'w');
chmod($uploadfile, 0777);
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
if ($attach_id) {
set_post_thumbnail( $new_post_id, $attach_id );
}
if ($new_post_id) {
$data['status']='Post added Successfully.';
}
else{
$data['status']='post failed..';
}
}else{
$data['status']=' Please provide correct post details.';
}
return ($data);
}

The object parameter passed into the callback function is a WP_REST_REQUST object and has a get_body() method on it which returns the payload/post body of the HTTP Post Request.
function create_city_from_data(WP_REST_Request $req) {
$body = $req->get_body()
return ['req' => $body];
}
I learnt about this today whilst reading this article
You can also declare the type of object in the method signature in case you need to search the documentation for it (like i have above).

CURL request :
$url = $your_url; // your url should like: http://host.com/wp-json/v1/'.$key
$post_string = json_encode($post_data);// make json string of post data
$ch = curl_init(); //curl initialisation
curl_setopt($ch, CURLOPT_URL, $url); // add url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get return value
curl_setopt($ch, CURLOPT_POST, true); // false for GET request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); // add post data
curl_setopt($crl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($post_string))
);// add header
$output = curl_exec($ch);
curl_close($ch); // close curl
$error = curl_error($ch); // get error
if(!$error){
return json_decode($output);
}else{
return $error;
}
For Handle Request in PLUGIN context :
public static function handle_requests(WP_REST_Request $request){
$return_data = [];
//get GET params
$key = $request['key'];
//get POST values
$post_data = json_decode($request->get_body());
//$return_data = $post_data;
if ( empty( $return_data ) ) {
return new WP_Error( 'error', 'Invalid Request', array( 'status' => 404 ) );
}else{
return $return_data;
}
}
Your WP REST API ACTION :
add_action( 'rest_api_init', function () {
register_rest_route( '/v1', '/(?P<key>[\w]+)', array(
'methods' => ['GET', 'POST'],
'callback' => 'YOUR_CLASS::handle_requests',
'permission_callback' => '__return_true'
) );
} );
//permission_callback need to add for wordpress newer versions.

Related

How can i use login_url in inline_keyboard Telegram bot php

I have
$inline_button1 = array("text"=>"Text","login_url"=>array("url" => "https://example.com"));
$inline_keyboard = [[$inline_button1]];
$keyboard=array("inline_keyboard"=>$inline_keyboard);
$replyMarkup = json_encode($keyboard);
$tg->send2($id, 'Test', $replyMarkup);
Function send2 look as
public function send2($id, $message, $reply) {
$data = array(
'chat_id' => $id,
'text' => $message,
'reply_markup' => $reply,
'parse_mode' => 'html',
);
$out = $this->request('sendMessage', $data);
return $out;
}
If i use 'url' instead 'login_url' it works fine.
I find the problem, it was needed specify parameter DOMAIN in botfather setting

Custom post type API custom endpoint for single post by ID

I've created a WordPress custom post type, then I've created REST API custom endpoint to GET all the posts works ok. Then I've created another custom endpoint to GET single post by ID. For example http://localhost:8888/wordpress/wp-json/lc/v1/cars/120
I have created a few posts, each time I change the ID at the end of the route to 118 or 116 it shows the same data for the latest post-ID 120. I need the relevant data to show based on the post ID, I would appreciate any kind of help. Thanks
public function rest_posts_endpoints(){
register_rest_route(
'lc/v1',
'/cars/(?P<id>\d+)',
[
'method' => 'GET',
'callback' => [$this, 'rest_endpoint_handler_single'],
]
);
}
public function rest_endpoint_handler_single( WP_REST_Request $request ) {
$params = $request->get_query_params();
$args = [
'post_type' => 'cars',
'id' => $params['id'],
];
$post = get_posts($args);
$data['id'] = $post[0]->ID;
$data['slug'] = $post[0]->post_name;
$data['title'] = $post[0]->post_title;
$data['content'] = $post[0]->post_content;
$data['excerpt'] = $post[0]->post_excerpt;
return $data;
}
public function rest_endpoint_handler_single( WP_REST_Request $request ) {
$params = $request->get_params();
$args = [
'post_type' => 'cars',
'id' => $params['id'],
'include' => array($params['id']),
];
$post = get_posts($args);
$data['id'] = $post[0]->ID;
$data['slug'] = $post[0]->post_name;
$data['title'] = $post[0]->post_title;
$data['content'] = $post[0]->post_content;
$data['excerpt'] = $post[0]->post_excerpt;
return $data;
}

Add links on Wordpress custom endpoint

I created a custom endpoint for specific data from a custom table in my Wordpress plugin. It get's all the data from the table with the getHelpers() function. After that it will be merged by some user data. I would like to add the profile_image as a link to the response so we can get it with the embed parameter.
What is the best way to add the link to the response? I know the $response->add_link() function but this would add it to the response and not to each contributor.
I tried to add the link as an array but this won't react on the _embed parameter.
This is my code for the custom endpoint:
class VEMS_Rest_Contributors extends WP_REST_Controller {
protected $namespace = 'vems/v2';
protected $rest_base = 'contributors';
/**
* Register the routes for coupons.
*/
public function register_routes() {
register_rest_route( $this->namespace, '/' . $this->rest_base, array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'args' => $this->get_collection_params(),
) );
}
public function get_items( WP_REST_Request $request ) {
$project_id = $request->get_param( 'project_id' );
$contributors = array();
if( !empty($project_id) ) {
$project = new VEMS_Project( $request['project_id'] );
$helpers = $project->getHelpers();
foreach($helpers as $helper) {
$contributor = array();
if( !empty($helper->contributor_id) ) {
$user = get_user_by( 'ID', $helper->contributor_id );
$user_meta = get_user_meta( $helper->contributor_id );
$contributor['ID'] = $helper->contributor_id;
$contributor['user_nicename'] = $user->data->display_name;
$contributor['user_profile_image'] = $user_meta['contributor_profile_image'][0];
} else {
$contributor['user_nicename'] = $helper->name;
$contributor['user_profile_image'] = $helper->image_id;
}
$contributor['item_total'] = $helper->item_total;
$contributor['checked'] = $helper->checked;
$contributor['helper_date'] = $helper->helper_date;
/*
$contributor['_links']['profile_image'] = array(
'href' => rest_url( '/wp/v2/media/' . $contributor['user_profile_image'] ),
'embeddable' => true
);
*/
$contributors[] = $contributor;
}
}
$response = rest_ensure_response( $contributors );
return $response;
}
public function get_collection_params() {
$params['project_id'] = array(
'description' => __( 'Limit result set to contributors assigned a specific project.', 'vems' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
);
return $params;
}
}
to handle links on route vems/v2/contributors?_embed, the element profile_image must be an array of links and then you can do that
$contributor['_links']['profile_image'] = [
[
'href' => rest_url( '/wp/v2/media/' . $contributor['ID'] ),
'embeddable' => true,
],
];

Not displayed in the article list until you click "Update" on the dashboard

I am challenging Ajax implementation when replying by "BBPress".
However, reply posted in this manner is displayed in the dashboard, but it is not displayed in the loop of the replies list.
This will be displayed in the loop of the replies list only when you click "Update" on the dashboard.
I want to know the code that displays correctly in the loop.
This is my code:
my-reply.js
"use strict";
(function($){
$(document).on("click","#bbp_reply_submit", function() {
// get
var inputForum = '56'; //There is only one forum.
var inputTopic = $('#bbp_topic_id').val();
var inputTitle = $('#bbp-reply-form-info').text();
var inputContent = $('#bbp_reply_input').val();
var inputParent = $('#bbp_reply_to').val();
var inputIp = $('#my_reply_ip').val();
// Ajax
$.ajax({
url: MY_AJAX.api,
type: 'POST',
data: {
// action name
action: MY_AJAX.action,
// nonce
nonce: MY_AJAX.nonce,
// submit data
submitForum: inputForum,
submitTopic: inputTopic,
submitTitle: inputTitle,
submitContent: inputContent,
submitParent: inputParent,
submitIp: inputIp,
}
})
// scusess
.done(function( response ) {
alert('success'); // Actually, I will display reply instead of alerts.
})
// error
.fail(function( jqXHR, textStatus, errorThrown ) {
alert('error');
});
});
})(jQuery);
functions.php
// nonce
function my_enqueue_scripts() {
$handle = 'my-script';
$jsFile = 'path/to/myscript.js';
wp_register_script($handle, $jsFile, ['jquery']);
$acrion = 'my-ajax-action';
wp_localize_script($handle, 'MY_AJAX', [
'api' => admin_url( 'admin-ajax.php' ),
'action' => $acrion,
'nonce' => wp_create_nonce( $acrion ),
]);
wp_enqueue_script($handle);
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
// post reply
function my_ajax_event() {
$action = 'my-ajax-action';
if( check_ajax_referer($action, 'nonce', false) ) {
$submitForum = esc_html( $_POST['submitForum'] );
$submitTopic = esc_html( $_POST['submitTopic'] );
$submitTitle = esc_html( $_POST['submitTitle'] );
$submitContent = esc_html( $_POST['submitContent'] );
$submitParent = esc_html( $_POST['submitParent'] );
$submitIp = esc_html( $_POST['submitIp'] );
$submitTopicslug = esc_html( $_POST['submitTopicslug'] );
$page = get_post( $submitTopic );
$slug = $page->post_name;
$date = 'Y-m-d H:i:s';
$my_post = array(
'post_title' => (string)wp_strip_all_tags($_POST['submitTitle']),
'post_content' => (string)$_POST['submitContent'],
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_type' => 'reply',
'meta_input' => array(
'_bbp_forum_id' => $_POST['submitForum'],
'_bbp_topic_id' => $_POST['submitTopic'],
'_bbp_reply_to' => $_POST['submitParent'],
'_bbp_author_ip' => $_POST['submitIp'],
'_edit_last' => get_current_user_id(),
'_bbp_topic_sort_desc' => 'dft',
'_bbp_sort_desc' => 'dft',
'_bbp_topic_sort_show_lead_topic' => 'dft',
'_bbp_topic_sort_show_lead_topic_forum' => 'dft',
'_wp_old_slug' => $slug,
'_bbp_last_active_time' => $date,
'_bbp_reply_count' => '',
'_bbp_engagement' => '',
'_bbp_reply_count_hidden' => '',
'_bbp_voice_count' => '',
)
);
wp_insert_post( $my_post );
} else {
status_header( '403' );
}
die();
}
add_action( 'wp_ajax_my-ajax-action', 'my_ajax_event' );
add_action( 'wp_ajax_nopriv_my-ajax-action', 'my_ajax_event' );

Wordpress XML-RPC and featured images

I'm currently developing a plugin for a client that takes an xml feed hourly and posts it into wordpress and I'm having trouble sending the featured image to the post.
I can post to wordpress fine but all my attempts to post the featured image have failed.
<?php
class XMLRPClientWordPress
{
var $XMLRPCURL = "";
var $UserName = "";
var $PassWord = "";
// Constructor
public function __construct($xmlrpcurl, $username, $password)
{
$this->XMLRPCURL = $xmlrpcurl;
$this->UserName = $username;
$this->PassWord = $password;
}
function send_request($requestname, $params)
{
$request = xmlrpc_encode_request($requestname, $params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $this->XMLRPCURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
public function create_post( $title, $body )
{
$title = htmlentities( $title, ENT_NOQUOTES, 'UTF-8' );
$content = array(
'post_category' => array( 18 ), // my category id
'post_type' => 'post',
'post_title' => $title,
'post_content' => $body,
'featured_image_url' => 'http://www.geekologie.com/2009/02/18/scary%20clown.jpg',
);
$params = array( 0, $this->UserName, $this->PassWord, $content );
return $this->send_request( 'wp.newPost', $params );
}
}
$objXMLRPClientWordPress = new XMLRPClientWordPress("xxxx/xmlrpc.php" , "xxxxx" , "xxxx");
$objXMLRPClientWordPress->create_post('Hey Chloe','Hope you like the clown');
?>
Is what i currently have, i've been reading the wordpress patch tickets on this issue but can't seem to figure out how to actually use the new features
Thanks
It should be something like this
'wp_post_thumbnail' => $pictureid
You have to get the ID of uploaded picture into variable and then assign it as a value of 'wp_post_thumbnail' parameter for 'metaWeblog.newPost'

Resources