Created
December 12, 2017 02:59
-
-
Save jackysee/72af69c5a077abf89300d72b744f0a8b to your computer and use it in GitHub Desktop.
Get embed tweet html with pic in wordpress
This file contains hidden or 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 | |
/* | |
The code below would help you to grap the twitter link in a string and return | |
the embeded HTML code, and replace twitter pic any. | |
I used it for reposting in my site (check https://indieweb.org/repost ) | |
require: twitteroauth ( https://github.com/abraham/twitteroauth ) | |
*/ | |
require "twitteroauth/autoload.php"; | |
function getStatus( $id ){ | |
$consumer_key = "xxx"; | |
$consumer_secret = "xxx"; | |
$access_token = "xxx"; | |
$access_token_secret = "xxx"; | |
$connection = new Abraham\TwitterOAuth\TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret); | |
$statuses = $connection->get("statuses/show/".$id, [ "tweet_mode"=>"extended" ]); | |
return $statuses; | |
} | |
function getMedia( $picUrl, $id ){ | |
$result = getStatus( $id ); | |
if (isset($result->entities->media)) { | |
foreach( $result->entities->media as $media ){ | |
if( $media->display_url == $picUrl){ | |
return '<div class="tweet-pic"><img src="' . $media->media_url_https . '" alt=""/></div>'; | |
} | |
} | |
} | |
return ""; | |
} | |
function getTweet($param){ | |
preg_match('/https:\/\/twitter\.com\/[^\/]+\/status\/(\d*)/', $param, $matches); | |
if( isset($matches[1]) ){ | |
$id = $matches[1]; | |
$query_args = array( 'id' => $id ); | |
$response = wp_remote_get( add_query_arg( $query_args, 'https://api.twitter.com/1/statuses/oembed.json' ) ); | |
if ( ! is_wp_error( $response ) ) { | |
$body = wp_remote_retrieve_body( $response ); | |
$tweet = json_decode( $body ); | |
$tweet_html = preg_replace("/<script.*<\/script>/", "", $tweet->html); | |
$tweet_html = preg_replace_callback( | |
"/pic\.twitter\.com\/[^<]*/", | |
function($matches) use ($id){ | |
return getMedia($matches[0], $id); | |
} | |
, $tweet_html ); | |
return Array( 'tweet' => $tweet, 'html' => $tweet_html); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment