Advertisement
Guest User

Open Graph protocol [Wordpress function]

a guest
Aug 18th, 2012
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 15.64 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: WP Facebook Open Graph protocol
  4. Plugin URI: http://wordpress.org/extend/plugins/wp-facebook-open-graph-protocol/
  5. Description: Adds proper Facebook Open Graph Meta tags and values to your site so when links are shared it looks awesome! Works on Google + and Linkedin too!
  6. Version: 2.0.4
  7. Author: Chuck Reynolds
  8. Author URI: http://chuckreynolds.us
  9. License: GPL2
  10. */
  11. /*
  12.     Copyright 2011 WordPress Facebook Open Graph protocol plugin (email: chuck@rynoweb.com)
  13.    
  14.     This program is free software; you can redistribute it and/or modify
  15.     it under the terms of the GNU General Public License, version 2, as
  16.     published by the Free Software Foundation.
  17.    
  18.     This program is distributed in the hope that it will be useful,
  19.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  20.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21.     GNU General Public License for more details.
  22.    
  23.     You should have received a copy of the GNU General Public License
  24.     along with this program; if not, write to the Free Software
  25.     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  26. */
  27.  
  28. define('WPFBOGP_VERSION', '2.0.4');
  29. wpfbogp_admin_warnings();
  30.  
  31. // add OGP namespace per ogp.me schema
  32. function wpfbogp_namespace($output) {
  33.     return $output.' xmlns:og="http://ogp.me/ns#"';
  34. }
  35. add_filter('language_attributes','wpfbogp_namespace');
  36.  
  37. // function to call first uploaded image in content
  38. function wpfbogp_find_images() {
  39.     global $post, $posts;
  40.    
  41.     // Grab content and match first image
  42.     $content = $post->post_content;
  43.     $output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches );
  44.    
  45.     // Make sure there was an image that was found, otherwise return false
  46.     if ( $output === FALSE ) {
  47.         return false;
  48.     }
  49.    
  50.     $wpfbogp_images = array();
  51.     foreach ( $matches[1] as $match ) {
  52.         // If the image path is relative, add the site url to the beginning
  53.         if ( ! preg_match('/^https?:\/\//', $match ) ) {
  54.             // Remove any starting slash with ltrim() and add one to the end of site_url()
  55.             $match = site_url( '/' ) . ltrim( $match, '/' );
  56.         }
  57.         $wpfbogp_images[] = $match;
  58.     }
  59.    
  60.     return $wpfbogp_images;
  61. }
  62.  
  63. function wpfbogp_start_ob() {
  64.     // Start the buffer before any output
  65.     ob_start( 'wpfbogp_callback' );
  66. }
  67.  
  68. function wpfbogp_callback( $content ) {
  69.     // Grab the page title and meta description
  70.     $title = preg_match( '/<title>(.*)<\/title>/', $content, $title_matches );
  71.     $decsription = preg_match( '/<meta name="description" content="(.*)"/', $content, $description_matches );
  72.    
  73.     // Take page title and meta description and place it in the ogp meta tags
  74.     if ( $title !== FALSE && count( $title_matches ) == 2 ) {
  75.         $content = preg_replace( '/<meta property="og:title" content="(.*)">/', '<meta property="og:title" content="' . $title_matches[1] . '">', $content );
  76.     }
  77.    
  78.     if ( $description !== FALSE && count( $description_matches ) == 2 ) {
  79.         $content = preg_replace( '/<meta property="og:description" content="(.*)">/', '<meta property="og:description" content="' . $description_matches[1] . '">', $content );
  80.     }
  81.    
  82.     return $content;
  83. }
  84.  
  85. function wpfbogp_flush_ob() {
  86.     ob_end_flush();
  87. }
  88.  
  89. add_action( 'init', 'wpfbogp_start_ob', 0 );
  90. add_action( 'wp_footer', 'wpfbogp_flush_ob', 10000 ); // Fire after other plugins (which default to priority 10)
  91.  
  92. // build ogp meta
  93. function wpfbogp_build_head() {
  94.     global $post;
  95.     $options = get_option('wpfbogp');
  96.     // check to see if you've filled out one of the required fields and announce if not
  97.     if ( ( ! isset( $options['wpfbogp_admin_ids'] ) || empty( $options['wpfbogp_admin_ids'] ) ) && ( ! isset( $options['wpfbogp_app_id'] ) || empty( $options['wpfbogp_app_id'] ) ) ) {
  98.         echo "\n<!-- Facebook Open Graph protocol plugin NEEDS an admin or app ID to work, please visit the plugin settings page! -->\n";
  99.     } else {
  100.         echo "\n<!-- WordPress Facebook Open Graph protocol plugin (WPFBOGP v".WPFBOGP_VERSION.") http://rynoweb.com/wordpress-plugins/ -->\n";
  101.        
  102.         // do fb verification fields
  103.         if ( isset( $options['wpfbogp_admin_ids'] ) && ! empty( $options['wpfbogp_admin_ids'] ) ) {
  104.             echo '<meta property="fb:admins" content="' . esc_attr( apply_filters( 'wpfbogp_app_id', $options['wpfbogp_admin_ids'] ) ) . '">' . "\n";
  105.         }
  106.         if ( isset( $options['wpfbogp_app_id'] ) && ! empty( $options['wpfbogp_app_id'] ) ) {
  107.             echo '<meta property="fb:app_id" content="' . esc_attr( apply_filters( 'wpfbogp_app_id', $options['wpfbogp_app_id'] ) ) . '">' . "\n";
  108.         }
  109.        
  110.         // do url stuff
  111.         if (is_home() || is_front_page() ) {
  112.             $wpfbogp_url = get_bloginfo( 'url' );
  113.         } else {
  114.             $wpfbogp_url = 'http' . (is_ssl() ? 's' : '') . "://".$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  115.         }
  116.         echo '<meta property="og:url" content="' . esc_url( apply_filters( 'wpfbogp_url', $wpfbogp_url ) ) . '">' . "\n";
  117.        
  118.         // do title stuff
  119.         if (is_home() || is_front_page() ) {
  120.             $wpfbogp_title = get_bloginfo( 'name' );
  121.         } else {
  122.             $wpfbogp_title = get_the_title();
  123.         }
  124.         echo '<meta property="og:title" content="' . esc_attr( apply_filters( 'wpfbogp_title', $wpfbogp_title ) ) . '">' . "\n";
  125.        
  126.         // do additional randoms
  127.         echo '<meta property="og:site_name" content="' . get_bloginfo( 'name' ) . '">' . "\n";
  128.        
  129.         // do descriptions
  130.         if ( is_singular() ) {
  131.             if ( has_excerpt( $post->ID ) ) {
  132.                 $wpfbogp_description = strip_tags( get_the_excerpt( $post->ID ) );
  133.             } else {
  134.                 $wpfbogp_description = str_replace( "\r\n", ' ' , substr( strip_tags( strip_shortcodes( $post->post_content ) ), 0, 160 ) );
  135.             }
  136.         } else {
  137.             $wpfbogp_description = get_bloginfo( 'description' );
  138.         }
  139.         echo '<meta property="og:description" content="' . esc_attr( apply_filters( 'wpfbogp_description', $wpfbogp_description ) ) . '">' . "\n";
  140.        
  141.         // do ogp type
  142.         if ( is_single() ) {
  143.             $wpfbogp_type = 'article';
  144.         } else {
  145.             $wpfbogp_type = 'website';
  146.         }
  147.         echo '<meta property="og:type" content="' . esc_attr( apply_filters( 'wpfbpogp_type', $wpfbogp_type ) ) . '">' . "\n";
  148.        
  149.         // Find/output any images for use in the OGP tags
  150.         $wpfbogp_images = array();
  151.        
  152.         // Only find images if it isn't the homepage and the fallback isn't being forced
  153.         if ( ! is_home() && $options['wpfbogp_force_fallback'] != 1 ) {
  154.             // Find featured thumbnail of the current post/page
  155.             if ( function_exists( 'has_post_thumbnail' ) && has_post_thumbnail( $post->ID ) ) {
  156.                 $thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
  157.                 $wpfbogp_images[] = $thumbnail_src[0]; // Add to images array
  158.             }
  159.            
  160.             if ( wpfbogp_find_images() !== false && is_singular() ) { // Use our function to find post/page images
  161.                 $wpfbogp_images = array_merge( $wpfbogp_images, wpfbogp_find_images() ); // Returns an array already, so merge into existing
  162.             }
  163.         }
  164.        
  165.         // Add the fallback image to the images array (which is empty if it's being forced)
  166.         if ( isset( $options['wpfbogp_fallback_img'] ) && $options['wpfbogp_fallback_img'] != '') {
  167.             $wpfbogp_images[] = $options['wpfbogp_fallback_img']; // Add to images array
  168.         }
  169.        
  170.         // Make sure there were images passed as an array and loop through/output each
  171.         if ( ! empty( $wpfbogp_images ) && is_array( $wpfbogp_images ) ) {
  172.             foreach ( $wpfbogp_images as $image ) {
  173.                 echo '<meta property="og:image" content="' . esc_url( apply_filters( 'wpfbogp_image', $image ) ) . '">' . "\n";
  174.             }
  175.         } else {
  176.             // No images were outputted because they have no default image (at the very least)
  177.             echo "<!-- There is not an image here as you haven't set a default image in the plugin settings! -->\n";
  178.         }
  179.        
  180.         // do locale // make lower case cause facebook freaks out and shits parser mismatched metadata warning
  181.         echo '<meta property="og:locale" content="' . strtolower( esc_attr( get_locale() ) ) . '">' . "\n";
  182.         echo "<!-- // end wpfbogp -->\n";
  183.     }
  184. }
  185.  
  186. add_action('wp_head','wpfbogp_build_head',50);
  187. add_action('admin_init','wpfbogp_init');
  188. add_action('admin_menu','wpfbogp_add_page');
  189.  
  190. // register settings and sanitization callback
  191. function wpfbogp_init() {
  192.     register_setting('wpfbogp_options','wpfbogp','wpfbogp_validate');
  193. }
  194.  
  195. // add admin page to menu
  196. function wpfbogp_add_page() {
  197.     add_options_page('Facebook Open Graph protocol plugin','Facebook OGP','manage_options','wpfbogp','wpfbogp_buildpage');
  198. }
  199.  
  200. // build admin page
  201. function wpfbogp_buildpage() {
  202. ?>
  203.  
  204. <div class="wrap">
  205.     <h2>Facebook Open Graph protocol plugin <em>v<?php echo WPFBOGP_VERSION; ?></em></h2>
  206.     <div id="poststuff" class="metabox-holder has-right-sidebar">
  207.         <div id="side-info-column" class="inner-sidebar">
  208.             <div class="meta-box-sortables">
  209.                 <div id="about" class="postbox">
  210.                     <h3 class="hndle" id="about-sidebar"><?php _e('About the Plugin:') ?></h3>
  211.                     <div class="inside">
  212.                         <p>Talk to <a href="http://twitter.com/chuckreynolds" target="_blank">@ChuckReynolds</a> on twitter or please fill out the <a href="http://rynoweb.com/wordpress-plugins/" target="_blank">plugin support form</a> for bugs or feature requests.</p>
  213.                         <p><?php _e('<strong>Enjoy the plugin?</strong>') ?><br />
  214.                         <a href="http://twitter.com/?status=I'm using @chuckreynolds's WordPress Facebook Open Graph plugin - check it out! http://rynoweb.com/wordpress-plugins/" target="_blank"><?php _e('Tweet about it') ?></a> <?php _e('and consider donating.') ?></p>
  215.                         <p><?php _e('<strong>Donate:</strong> A lot of hard work goes into building plugins - support your open source developers. Include your twitter username and I\'ll send you a shout out for your generosity. Thank you!') ?><br />
  216.                         <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
  217.                         <input type="hidden" name="cmd" value="_s-xclick">
  218.                         <input type="hidden" name="hosted_button_id" value="GWGGBTBJTJMPW">
  219.                         <input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
  220.                         <img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
  221.                         </form></p>
  222.                     </div>
  223.                 </div>
  224.             </div>
  225.            
  226.             <div class="meta-box-sortables">
  227.                 <div id="about" class="postbox">
  228.                     <h3 class="hndle" id="about-sidebar"><?php _e('Relevant Information:') ?></h3>
  229.                     <div class="inside">
  230.                         <p><a href="http://ogp.me" target="_blank">The Open Graph Protocol</a><br />
  231.                         <a href="https://developers.facebook.com/docs/opengraph/" target="_blank">Facebook Open Graph Docs</a><br />
  232.                         <a href="https://developers.facebook.com/docs/insights/" target="_blank">Insights: Domain vs App vs Page</a><br />
  233.                         <a href="https://developers.facebook.com/docs/reference/plugins/like/" target="_blank">How To Add a Like Button</a></p>
  234.                     </div>
  235.                 </div>
  236.             </div>
  237.         </div> <!-- // #side-info-column .inner-sidebar -->
  238.  
  239.  
  240.         <div id="post-body" class="has-sidebar">
  241.             <div id="post-body-content" class="has-sidebar-content">
  242.                 <div id="normal-sortables" class="meta-box-sortables">
  243.                     <div id="about" class="postbox">
  244.                         <div class="inside">
  245.  
  246.         <form method="post" action="options.php">
  247.             <?php settings_fields('wpfbogp_options'); ?>
  248.             <?php $options = get_option('wpfbogp'); ?>
  249.  
  250.         <table class="form-table">
  251.             <tr valign="top">
  252.                 <th scope="row"><?php _e('Facebook User Account ID:') ?></th>
  253.                 <td><input type="text" name="wpfbogp[wpfbogp_admin_ids]" value="<?php echo $options['wpfbogp_admin_ids']; ?>" class="regular-text" /><br />
  254.                     <?php _e('For personal sites use your Facebook User ID here. <em>(You can enter multiple by separating each with a comma)</em>, if you want to receive Insights about the Like Buttons. The meta values will not display in your site until you\'ve completed this box.<br />
  255.                     <strong>Find your ID</strong> by going to the URL like this: http://graph.facebook.com/yourusername') ?></td>
  256.             </tr>
  257.             <tr valign="top">
  258.                 <th scope="row"><?php _e('Facebook Application ID:') ?></th>
  259.                 <td><input type="text" name="wpfbogp[wpfbogp_app_id]" value="<?php echo $options['wpfbogp_app_id']; ?>" class="regular-text" /><br />
  260.                     <?php _e('For business and/or brand sites use Insights on an App ID as to not associate it with a particular person. You can use this with or without the User ID field. Create an app and use the "App ID": <a href="https://www.facebook.com/developers/apps.php" target="_blank">Create FB App</a>.') ?></td>
  261.             </tr>
  262.             <tr valign="top">
  263.                 <th scope="row"><?php _e('Default Image URL to use:') ?></th>
  264.                 <td><input type="text" name="wpfbogp[wpfbogp_fallback_img]" value="<?php echo $options['wpfbogp_fallback_img']; ?>" class="large-text" /><br />
  265.                     <?php _e('Full URL including http:// to the default image to use if your posts/pages don\'t have a featured image or an image in the content. <strong>The image is recommended to be 200px by 200px</strong>.<br />
  266.                     You can use the WordPress <a href="upload.php">media uploader</a> if you wish, just copy the location of the image and put it here.') ?></td>
  267.             </tr>
  268.             <tr valign="top">
  269.                 <th scope="row"><?php _e('Force Fallback Image as Default') ?></th>
  270.                 <td><input type="checkbox" name="wpfbogp[wpfbogp_force_fallback]" value="1" <?php if ($options['wpfbogp_force_fallback'] == 1) echo 'checked="checked"'; ?>) /> <?php _e('Use this if you want to use the Default Image for everything instead of looking for featured/content images.') ?></label></td>
  271.             </tr>
  272.         </table>
  273.        
  274.         <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
  275.         </form>
  276.         <br class="clear" />
  277.                     </div>
  278.                 </div>
  279.             </div>
  280.         </div>
  281.     </div>
  282.     </div>
  283. </div>
  284. <?php
  285. }
  286.  
  287. // sanitize inputs. accepts an array, return a sanitized array.
  288. function wpfbogp_validate($input) {
  289.     $input['wpfbogp_admin_ids'] = wp_filter_nohtml_kses($input['wpfbogp_admin_ids']);
  290.     $input['wpfbogp_app_id'] = wp_filter_nohtml_kses($input['wpfbogp_app_id']);
  291.     $input['wpfbogp_fallback_img'] = wp_filter_nohtml_kses($input['wpfbogp_fallback_img']);
  292.     $input['wpfbogp_force_fallback'] = ($input['wpfbogp_force_fallback'] == 1)  ? 1 : 0;
  293.     return $input;
  294. }
  295.  
  296. // run admin notices on activation or if settings not set
  297. function wpfbogp_admin_warnings() {
  298.     global $wpfbogp_admins;
  299.         $wpfbogp_data = get_option('wpfbogp');
  300.     if ((empty($wpfbogp_data['wpfbogp_admin_ids']) || $wpfbogp_data['wpfbogp_admin_ids'] == '') && (empty($wpfbogp_data['wpfbogp_app_id']) || $wpfbogp_data['wpfbogp_app_id'] == '')) {
  301.         function wpfbogp_warning() {
  302.             echo "<div id='wpfbogp-warning' class='updated fade'><p><strong>".__('WP FB OGP is almost ready.')."</strong> ".sprintf(__('You must <a href="%1$s">enter your Facebook User ID or App ID</a> for it to work.'), "options-general.php?page=wpfbogp")."</p></div>";
  303.         }
  304.     add_action('admin_notices', 'wpfbogp_warning');
  305.     }
  306. }
  307.  
  308. // twentyten and twentyeleven add crap to the excerpt so lets check for that and remove
  309. add_action('after_setup_theme','wpfbogp_fix_excerpts_exist');
  310. function wpfbogp_fix_excerpts_exist() {
  311.     remove_filter('get_the_excerpt','twentyten_custom_excerpt_more');
  312.     remove_filter('get_the_excerpt','twentyeleven_custom_excerpt_more');
  313. }
  314.  
  315. // add settings link to plugins list
  316. function wpfbogp_add_settings_link($links, $file) {
  317.     static $this_plugin;
  318.     if (!$this_plugin) $this_plugin = plugin_basename(__FILE__);
  319.     if ($file == $this_plugin){
  320.         $settings_link = '<a href="options-general.php?page=wpfbogp">'.__("Settings","wpfbogp").'</a>';
  321.         array_unshift($links, $settings_link);
  322.     }
  323.     return $links;
  324. }
  325. add_filter('plugin_action_links','wpfbogp_add_settings_link', 10, 2 );
  326.  
  327. // lets offer an actual clean uninstall and rem db row on uninstall
  328. if (function_exists('register_uninstall_hook')) {
  329.     register_uninstall_hook(__FILE__, 'wpfbogp_uninstall_hook');
  330.     function wpfbogp_uninstall_hook() {
  331.         delete_option('wpfbogp');
  332.     }
  333. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement