How to integrate weather api in wordpress - wordpress

Please anyone help me how to integrate a api in wordpress api is in json formate
https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22
Iam using this code but im not able to display temprature
<?php
$url = 'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22';
$response = wp_remote_get( $url );
if( is_array($response) ) {
$header = $response['headers']; // array of http header lines
$body = $response['body']; // use the content
print_r(($body));
}
?>

Abu,
Put the code somewhere useful in wordpress so you can use the wp_remote_get
Understand the structure of the response (just putting the url in firefox address bar will give JSON structure
Understand that you receiving JSON, and decode it http://php.net/manual/en/function.json-decode.php
Find the temperature in the structure and use that as per code example below. Slightly freak out when you see the number but then ...
Read the API FAQ https://openweathermap.desk.com/customer/en/portal/articles/1996493-switching-between-temperature-units and realise the number is in Kelvin
I'll leave it to you to research how to request temp in Celcius or Fahrenheit
function show_temp() {
$url = 'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22';
$response = wp_remote_get( $url );
if( is_array($response) ) {
$header = $response['headers']; // array of http header lines
$body = $response['body']; // use the content
$resp = json_decode($body);
echo 'The temp in Kelvin is: '.$resp->main->temp;
echo '<pre>'.print_r($resp, true).'</pre>';
}
}
add_shortcode ('show_temp', 'show_temp');

Related

How to translate order status on API response

Is there any way how to translate order status on API response
“https://test.com/wp-json/wc/v3/orders “.
{
“status”: “processing”,
}
Thank you
In order to use this in PHP, we need to translate it to a format that PHP understands. To do this, we can use the json_decode() function.
$json = '{"key":"value"}';
// Translate into an object
$obj = json_decode( $json );
// Translate into an array
$array = json_decode( $json, true );

Convert post permalink to real post id for live and stage site

I am in a mesh and need some help.
There are three actor evolved.
Live Site / Production Site (wordpress)
Local Site / Stage / Testing Site (wordpress)
Third party analytic
Background:
I know its very bad but the fact is that the production sites and local sites content are not synced. i.e post id 1 in production can be as post id 24 in local.
Problem Definition:
I was assigned to use the third party's API to grab the list of top post with maximum hits and show it in our website.
$result = file_get_contents($url);
$result_json = json_decode($result, true);
The above lines did that for me easily.
Error:
Since the 3rd party did not had post excerpt, they send URL, image_link, hit_count, post title and author information as JSON.
So on my site I was able to show all these fields very well. But the problem started when my manager added post excerpt to the list.
I tried converting URL to postid and got the post excerpt using:
get_the_excerpt(url_to_postid($top_posts['link']))
It worked for live site. but in the stage and local its not working.
Well post URL has its domain name. Even when I replaced the domain name with my local or stage domain. its not showing any thing. and for some post when it shows the excerpt its not from the same article.
Guys need some idea.
Is there some way that I can get slug from URL?
I tried using explode() function. But sometime the slug is not the last item in array.
Thank you for reading it all. I appreciate you help.
For now I came with a solution. Primarily Using the URL to get post ID, if not found using post title to get the post id.
public static function get_excerpt ( $id = null ) {
$post = get_post($id);
if ( empty($post) ) {
return '';
}
if ( strlen($post->post_excerpt) ) {
// Use the excerpt
$excerpt = $post->post_excerpt;
$excerpt = apply_filters('the_excerpt', $excerpt);
} else {
// Make excerpt
$content = $post->post_content;
$content = strip_shortcodes($content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
$excerpt_length = apply_filters('excerpt_length', 55);
$excerpt_more = apply_filters('excerpt_more', ' ' . '[…]');
$excerpt = wp_trim_words($content, $excerpt_length, $excerpt_more);
$excerpt = wpautop($excerpt);
}
return apply_filters('wp_trim_excerpt', $excerpt);
}
Called this function to get the excerpt.
$postid = url_to_postid($top_posts['link']);
$postid = $postid!=0 ? $postid : get_page_by_title($post_title, OBJECT, 'post')->ID;
$excerpt = self::get_excerpt($postid);
This worked in my case as I didn't have posts with same title.
I am still waiting for some better solution to my problem.

File path without domain name from wp_get_attachment_url()

wp_get_attachment_url() process full file path like
http://example.com/wp-content/uploads/2014/12/aura.mp3
I want the url without http://example.com/
So, I want above example as wp-content/uploads/2014/12/aura.mp3 instead of http://example.com/wp-content/uploads/2014/12/aura.mp3. How to do it?
You can really easily explode it by / and then take the part with index 3. Example
$url = wp_get_attachment_url(id); //id is file's id
$urllocal = explode(site_url(), $url)[1]; //output local path
Here is the WordPress way using WordPress functions (avoid hacking):
$fullsize_path = get_attached_file( $attachment_id ); // Full path
$filename_only = basename( get_attached_file( $attachment_id ) ); // Just the file name
WordPress has tons of functions, so first try to find the function on the docs: https://developer.wordpress.org/reference/functions/get_attached_file/
You can use PHP's function explode.
Here is the code:
<?php
$image_url = wp_get_attachment_url( 9 ); //ID of your attachment
$my_image_url = explode('/',$image_url,4);
echo $my_image_url[3];
?>
You can implode your entire url on / and array_slice from the end, then implode it back in on /.
$url = wp_get_attachment_url($item->ID); //id is file's id
$url_relative = implode(array_slice(explode('/', $url),-3,3),'/');
//Returns: 2019/08/image.jpg
That way if your WordPress is on a subdomain or localhost or the images are on S3 it won't crash.

wordpress site integration with rest API

I'm trying to integrate with zoom.us, they have their guides here - https://support.zoom.us/hc/en-us/articles/201363053-Meeting-API
When someone schedules a meeting, the scheduler creates a post, which I pick up and call this function:
function scheduler_zoom_integration($post_id) {
$postdata = get_post($post_id);
$appointment_id = get_post_meta( $post_id, '_birs_appointment_id', true );
if (!empty($appointment_id)) {
$conference_details = schedule_meeting();
add_post_meta($appointment_id,'appointment_zoom_details', $conference_details, true);
}
}
add_action('publish_post', 'scheduler_zoom_integration');
Inside that function I call the schedule_meeting function that is using the REST API from zoom to get the meeting details including the link people will click to join the meeting.
function schedule_meeting($coach_id, $appointment_id, $start_time) {
$api_key = 'xxxxxxxxxxxxxxxxxxxxxxx';
$api_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$coach_zoom_id = get_user_meta($coach_id, 'coachzoomid', true);
$url = 'https://api.zoom.us/v1/meeting/create?api_key='.$api_key.'&api_secret='.$api_secret.'&data_type=JSON&host_id='.$coach_zoom_id.'&topic=health&type=2&start_time='.$start_time.'&duration=30&timezone=GMT-7:00&option_jbh=true&option_start_type=video';
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$response = fopen($url, 'r', false, $context);
fpassthru($response);
$response = json_decode($response);
fclose($response);
return $response;
}
I'm looking to get feedback on how I'm performing this function as I've never done a REST API before. Should I use fopen / fclose? How do I make the call to begin with? Any help is appreciated.
You should try using WordPress' built in HTTP API. It has helper functions for doing HTTP calls. I see you're doing a GET so check out:
http://codex.wordpress.org/Function_Reference/wp_remote_get
Note that it returns WP_Error class on failure.

Wordpress XML-RPC post success but don't work with long body

I use code below to post via XML-RPC, it does success. But when I send a long string $bodypost, my post doesn't have body content. I test it with html code, it's working, then I remove all space, my $bodypost just have 1 line with about 4000 words, it's not working.
How can I fix it?
<?php
function send_post($titlepost, $bodypost, $categorypost, $keywordspost )
{
require_once("IXR_Library.php.inc");
$encoding='UTF-8';
$client->debug = false; //Set it to false in Production Environment
$title= $titlepost; // $title variable will insert your blog title
$body= $bodypost; // $body will insert your blog content (article content)
$category=$categorypost; // Comma seperated pre existing categories. Ensure that these categories exists in your blog.
$keywords=$keywordspost;
$customfields=array('key'=>'Author-bio', 'value'=>'Autor Bio Here'); // Insert your custom values like this in Key, Value format
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);
$content = array(
'title'=>$title,
'description'=>$body,
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array($category),
'custom_fields' => array($customfields)
);
// Create the client object
$client = new IXR_Client('http://www.domain.com/xmlrpc.php');
$username = "abc";
$password = "abc";
$params = array(0,$username,$password,$content,true); // Last parameter is 'true' which means post immideately, to save as draft set it as 'false'
// Run a query for PHP
if (!$client->query('metaWeblog.newPost', $params)) {
die('Something went wrong - '.$client->getErrorCode().' : '.$client->getErrorMessage());
}
else
echo "Article Posted Successfully";
}
?>
I found how to fix it. This code does not work if my body code is give by source code of default Wordpress editor, but if I change it to CkEditor it's working!

Resources