Last active
April 8, 2023 22:43
-
-
Save kingkool68/c2e3b2c64609a3dc39939ac57773dc5b to your computer and use it in GitHub Desktop.
A brief example of working with an external API in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// In this brief example we'll scrape an Instagram post and save it as a WordPress post | |
// Go to a URL and get the contents back | |
// See https://developer.wordpress.org/reference/functions/wp_remote_get/ | |
$instagram_request = wp_remote_get( 'https://www.instagram.com/p/BSBvNVIF8tI/' ); | |
// If it's succesful, the payload of the request will be in $instagram_request['body'] | |
$instagram_html = $instagram_request['body']; | |
// Instagram includes JSON data about the post within the HTML of the page. | |
// With a bit of parsing we can get that JSON data into something we can use in PHP | |
// Via https://github.com/raiym/instagram-php-scraper/blob/849f464bf53f84a93f86d1ecc6c806cc61c27fdc/src/InstagramScraper/Instagram.php#L32 | |
$arr = explode( 'window._sharedData = ', $instagram_html ); | |
$json = explode( ';</script>', $arr[1] ); | |
$json = $json[0]; | |
$instagram_json = json_decode( $json ); | |
// To see the data in $instagram_json refer to http://www.jsoneditoronline.org/?id=9e77af0c63b3aab427e2cb506e374a1e | |
// Instagram has a very verbose structure for its data that we can simplify to work with | |
$instagram_node = $instagram_json->entry_data->PostPage[0]->graphql->shortcode_media; | |
// Let's get the URL src of the image | |
$img_src = $instagram_node->display_url; | |
// Lets get the description | |
$description = $instagram_node->edge_media_to_caption->edges[0]->node->text | |
// And the Instagram permalink | |
// i.e. https://www.instagram.com/p/BSBvNVIF8tI/ | |
$permalink = 'https://www.instagram.com/p/' . $instagram_node->shortcode . '/'; | |
// Now let's make a WordPress post | |
$post_content = '<img src="' . $img_src . '">'; | |
$post_content .= '<p>' . $description . '</p>'; | |
$post_content .= '<p>via <a href="' . $permalink . '">' . $permalink . '</a></p>'; | |
$new_post = array( | |
'post_content' => $post_content, | |
'post_title' => 'My Instagram Post', | |
'post_status' => 'publish', | |
); | |
// Create a new post with the details we provided | |
wp_insert_post( $new_post ); | |
// Now every time this code is run it will fetch data from Instagram, parse it, and save a new post |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment