Created
January 9, 2019 19:04
-
-
Save NasirNobin/84583702a736a6ae1dbccf532629d601 to your computer and use it in GitHub Desktop.
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 | |
| /** | |
| * Auto post to facebook from wordpress/website | |
| * Author -> Nasir Uddin Nobin | |
| */ | |
| function fb_update($ID, $post){ | |
| /** | |
| * download facebook php sdk https://github.com/facebookarchive/facebook-php-sdk | |
| * upload it to your directory and include it | |
| * if you paste this code to plugin file use (plugin_dir_path(__FILE__) | |
| */ | |
| require_once (get_template_directory_uri().'/facebook-php-sdk/autoload.php'); | |
| // cleaning html tags and bbcodes | |
| $content = strip_tags($post->post_content); | |
| $content = preg_replace("/\[.+\](.+)|\s\s+\[\/.+\]/i", "$1", $content); | |
| // getting $permalink from id | |
| $permalink = get_permalink( $ID ); | |
| $fb = new Facebook\Facebook([ | |
| 'app_id' => '{your-ap-id}', // your app id | |
| 'app_secret' => '{app-secret}', // your app secret | |
| 'default_graph_version' => 'v2.2', | |
| ]); | |
| /** | |
| * generate your page long live access token | |
| * you may use https://developers.facebook.com/tools/explorer | |
| * Permissions: manage_pages, publish_pages | |
| */ | |
| $accessToken='{give-your-long-live-page-access-token}'; | |
| $linkData = [ | |
| 'link' => $permalink, | |
| 'message' => short_content($content,$num=35)." | |
| Read more: {$permalink} | |
| ",]; | |
| try{ | |
| $response = $fb->post('/me/feed', $linkData, $accessToken); | |
| } | |
| catch(Facebook\Exceptions\FacebookResponseException $e) { } | |
| catch(Facebook\Exceptions\FacebookSDKException $e) { } | |
| } | |
| function short_content($content,$num=30) { | |
| $limit = $num+1; | |
| $excerpt = explode(' ', $content, $limit); | |
| array_pop($excerpt); | |
| $excerpt = implode(" ",$excerpt); | |
| return $excerpt."..."; | |
| } | |
| add_action( 'publish_post', 'fb_update', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment