This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: jamm on Sep 8th, 2012  |  syntax: None  |  size: 12.13 KB  |  views: 101  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2. /*
  3. Plugin Name: Google XML Sitemap for Videos
  4. Plugin URI: http://www.labnol.org/software/xml-video-sitemaps-for-google/14085/
  5. Description: This plugin will generate a XML Video Sitemap for your WordPress blog. Open the <a href="tools.php?page=video-sitemap-generate-page">settings page</a> to create your video sitemap.
  6. Author: Amit Agarwal
  7. Version: 2.6
  8. Author URI: http://www.labnol.org/
  9. */
  10. register_activation_hook(__FILE__, 'my_activation');
  11. function my_activation()
  12. {
  13.         add_option( "sitemap_include_video_length", "0", "", "no" );
  14. }
  15.  
  16. register_deactivation_hook(__FILE__, 'my_deactivation');
  17. function my_deactivation()
  18. {
  19.         delete_option("sitemap_include_video_length");
  20.         if(wp_get_schedule('my_hourly_hook'))
  21.                 wp_clear_scheduled_hook("my_hourly_hook");
  22. }
  23. add_action("my_hourly_hook","my_hourly_function");
  24. function my_hourly_function()
  25. {
  26.         if((time()- @filemtime($_SERVER["DOCUMENT_ROOT"] . '/sitemap-video.xml')) > (60*60*24)) //if sitemap age > a day, update sitemap
  27.         {
  28.                 video_sitemap_loop();
  29.         }
  30. }
  31.  
  32. add_action ('admin_menu', 'video_sitemap_generate_page');
  33.  
  34. function video_sitemap_generate_page () {
  35.     if (function_exists ('add_submenu_page'))
  36.         add_submenu_page ('tools.php', __('Video Sitemap'), __('Video Sitemap'),
  37.             'manage_options', 'video-sitemap-generate-page', 'video_sitemap_generate');
  38. }
  39.  
  40.     /**
  41.      * Checks if a file is writable and tries to make it if not.
  42.      *
  43.      * @since 3.05b
  44.      * @access private
  45.      * @author  VJTD3 <http://www.VJTD3.com>
  46.      * @return bool true if writable
  47.      */
  48.     function IsVideoSitemapWritable($filename) {
  49.         //can we write?
  50.         if(!is_writable($filename)) {
  51.             //no we can't.
  52.             if(!@chmod($filename, 0666)) {
  53.                 $pathtofilename = dirname($filename);
  54.                 //Lets check if parent directory is writable.
  55.                 if(!is_writable($pathtofilename)) {
  56.                     //it's not writeable too.
  57.                     if(!@chmod($pathtoffilename, 0666)) {
  58.                         //darn couldn't fix up parrent directory this hosting is foobar.
  59.                         //Lets error because of the permissions problems.
  60.                         return false;
  61.                     }
  62.                 }
  63.             }
  64.         }
  65.         //we can write, return 1/true/happy dance.
  66.         return true;
  67.     }
  68.  
  69.  
  70. function video_sitemap_generate () {
  71.         if($_POST['submit'])
  72.                 update_option("sitemap_include_video_length",$_POST['time']);
  73.        
  74.     if ($_POST ['submit'] == "Generate Video Sitemap") {
  75.         $st = video_sitemap_loop ();
  76.         if (!$st) {
  77. echo '<br /><div class="error"><h2>Oops!</h2><p>Looks like none of your blog posts contain YouTube videos. Please publish a test post containing a YouTube video and regnerate the video sitemap.</p><p>If the issue remains unresolved, please post the error message in this <a target="_blank" href="http://wordpress.org/tags/xml-sitemaps-for-videos?forum_id=10#postform">WordPress forum</a>.</p></div>';    
  78. exit();
  79. }
  80.  
  81. ?>
  82.  
  83. <div class="wrap">
  84.   <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];
  85. if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
  86.   <div style="width:800px; padding:10px 20px; background-color:#eee; font-size:.95em; font-family:Georgia;margin:20px">
  87.     <h2>XML Sitemap for Vidoes</h2>
  88.     <?php $sitemapurl = get_bloginfo('url') . "/sitemap-video.xml"; ?>
  89.     <p>The <a target="_blank" href="<?php echo $sitemapurl; ?>">XML Sitemap</a> was generated successfully and you can <a target="_blank" href="http://www.google.com/webmasters/sitemaps/ping?sitemap=<?php echo $sitemapurl; ?>">ping Google</a> to inform them about your updated sitemap.</p>
  90.     <p>This WordPress Plugin is written by <a href="http://www.labnol.org/about/">Amit Agarwal</a> of <a href="http://www.labnol.org/">Digital Inspiration</a>. For feedback or suggestions on improving this plugin, please send me an email at amit@labnol.org</p>
  91.     <p><a href="https://twitter.com/labnol" class="twitter-follow-button" data-show-count="false" data-lang="en">Follow @labnol</a>
  92.       <iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fdigital.inspiration&amp;send=false&amp;layout=button_count&amp;width=300&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font=arial&amp;height=24&amp;appId=197498283654348" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:300px; height:20px;" allowTransparency="true"></iframe>
  93.     </p>
  94.   </div>
  95. </div>
  96. <?php exit; } elseif($_POST['submit']=="Automate Sitemap Generation") {
  97.         wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_hook');
  98. } elseif($_POST['submit']=="Deactivate Sitemap Generation") {
  99.         wp_clear_scheduled_hook("my_hourly_hook");
  100.  } ?>
  101. <div class="wrap">
  102.   <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
  103.   <div style="width:800px; padding:10px 20px; background-color:#eee; font-size:.95em; font-family:Georgia;margin:20px">
  104.     <h2>XML Sitemap for Videos</h2>
  105.     <p>Sitemaps are a way to tell Google and other search engines about web pages, images and video content on your site that they may otherwise not discover. </p>
  106.     <form id="options_form" method="post" action="">
  107.       <input type="checkbox" id="sboption" name="time" value="1" <?php if(get_option("sitemap_include_video_length") == "1") echo 'checked="checked"';?> />
  108.       <label for="sboption">Include video length? (Not recommended for sites will large number of videos)</label>
  109.       <div class="submit">
  110.         <input type="submit" name="submit" id="sb_submit" value="Generate Video Sitemap" />
  111.                 <br/><br/><span>Automatically generate sitemap once per day : </span><br/><br/>
  112.                 <input type="submit" name="submit" id="sb_submit" value="<?php echo (wp_get_schedule('my_hourly_hook'))? "Deactivate Sitemap Generation":"Automate Sitemap Generation"; ?>" />
  113.       </div>
  114.     </form>
  115.     <p>Click the button above to generate a Video Sitemap for your website. Once you have created your Sitemap, you can submit it to Google using Webmaster Tools. </p>
  116.     <p>You may also want to create separate <a href="http://wordpress.org/extend/plugins/google-image-sitemap/">Image Sitemap</a> and <a href="http://wordpress.org/extend/plugins/google-mobile-sitemap/">Mobile Sitemap</a> for improving your site's visibility in Google.</p>
  117.     <p>This WordPress Plugin is written by <a href="http://www.labnol.org/about/">Amit Agarwal</a> of <a href="http://www.labnol.org/">Digital Inspiration</a>. </p>
  118.   </div>
  119. </div>
  120. <?php
  121. }
  122.  
  123. function video_sitemap_loop () {
  124.     global $wpdb;
  125.         $include_video_length=get_option("sitemap_include_video_length");
  126.     $posts = $wpdb->get_results ("SELECT id, post_title, post_content, post_date_gmt, post_excerpt
  127.     FROM $wpdb->posts WHERE post_status = 'publish'
  128.     AND (post_type = 'post' OR post_type = 'page')
  129.     AND post_content LIKE '%youtube.com%'
  130.     ORDER BY post_date DESC");
  131.  
  132.     if (empty ($posts)) {
  133.         return false;
  134.  
  135.     } else {
  136.  
  137.         $xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";      
  138.         $xml .= '<!-- Created by (http://wordpress.org/extend/plugins/xml-sitemaps-for-videos/) -->' . "\n";
  139.         $xml .= '<!-- Generated-on="' . date("F j, Y, g:i a") .'" -->' . "\n";            
  140.         $xml .= '<?xml-stylesheet type="text/xsl" href="' . get_bloginfo('wpurl') . '/wp-content/plugins/xml-sitemaps-for-videos/video-sitemap.xsl"?>' . "\n" ;        
  141.         $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">' . "\n";
  142.        
  143.         $videos = array();
  144.    
  145.         foreach ($posts as $post) {
  146.             $c = 0;
  147.             if (preg_match_all ("/youtube.com\/(v\/|watch\?v=|embed\/)([a-zA-Z0-9\-_]*)/", $post->post_content, $matches, PREG_SET_ORDER)) {
  148.  
  149.                     $excerpt = ($post->post_excerpt != "") ? $post->post_excerpt : $post->post_title ;
  150.                     $permalink = get_permalink($post->id);
  151.  
  152.                 foreach ($matches as $match) {
  153.                                    
  154.                         $id = $match [2];
  155.                         $fix =  $c++==0?'':' [Video '. $c .'] ';
  156.                        
  157.                         if (in_array($id, $videos))
  158.                             continue;
  159.                            
  160.                         array_push($videos, $id);
  161.                        
  162.                         $xml .= "\n <url>\n";
  163.                         $xml .= " <loc>$permalink</loc>\n";
  164.                         $xml .= " <video:video>\n";
  165.                         $xml .= "  <video:player_loc allow_embed=\"yes\" autoplay=\"autoplay=1\">http://www.youtube.com/v/$id</video:player_loc>\n";
  166.                         $xml .= "  <video:thumbnail_loc>http://i.ytimg.com/vi/$id/hqdefault.jpg</video:thumbnail_loc>\n";
  167.                         $xml .= "  <video:title>" . htmlspecialchars($post->post_title) . $fix . "</video:title>\n";
  168.                         $xml .= "  <video:description>" . $fix . htmlspecialchars($excerpt) . "</video:description>\n";
  169.    
  170.                     if ($include_video_length == 1) {  
  171.                         $duration = youtube_duration ($id);
  172.                         if ($duration != 0)
  173.                             $xml .= "  <video:duration>".youtube_duration ($id)."</video:duration>\n";
  174.                             }
  175.  
  176.                     $xml .= "  <video:publication_date>".date (DATE_W3C, strtotime ($post->post_date_gmt))."</video:publication_date>\n";
  177.    
  178.                     $posttags = get_the_tags($post->id); if ($posttags) {
  179.                     $tagcount=0;
  180.                     foreach ($posttags as $tag) {
  181.                         if ($tagcount++ > 32) break;
  182.                         $xml .= "   <video:tag>$tag->name</video:tag>\n";
  183.                         }
  184.                     }    
  185.  
  186.                     $postcats = get_the_category($post->id); if ($postcats) {
  187.                     foreach ($postcats as $category) {
  188.                         $xml .= "   <video:category>$category->name</video:category>\n";
  189.                         break;
  190.                         }
  191.                     }        
  192.  
  193.                     $xml .= " </video:video>\n </url>";
  194.                 }
  195.             }
  196.         }
  197.  
  198.         $xml .= "\n</urlset>";
  199.     }
  200.     $video_sitemap_url = $_SERVER["DOCUMENT_ROOT"] . '/sitemap-video.xml';
  201.     if (IsVideoSitemapWritable($_SERVER["DOCUMENT_ROOT"]) || IsVideoSitemapWritable($video_sitemap_url)) {
  202.         if (file_put_contents ($video_sitemap_url, $xml)) {
  203.             return true;
  204.         }
  205.     }
  206. echo '<br /><div class="wrap"><h2>Error writing the file</h2><p>The XML sitemap was generated successfully but the  plugin was unable to save the xml to your WordPress root folder at <strong>' . $_SERVER["DOCUMENT_ROOT"] . '</strong> probably because the folder doesn\'t have appropriate <a href="http://codex.wordpress.org/Changing_File_Permissions" target="_blank">write permissions</a>.</p><p>You can however manually copy-paste the following text into a file and save it as video-sitemap.xml in your WordPress root folder. </p><br /><textarea rows="30" cols="150" style="font-family:verdana; font-size:11px;color:#666;background-color:#f9f9f9;padding:5px;margin:5px">' . $xml . '</textarea></div>';    
  207.     exit();
  208. }
  209.  
  210. # given a video id, get the duration.
  211. # might give this a delay to avoid running into issues with YouTube.
  212. function youtube_duration ($id) {
  213.     try {
  214.         $ch = curl_init ();
  215.         curl_setopt ($ch, CURLOPT_URL, "http://gdata.youtube.com/feeds/api/videos/$id");
  216.         curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  217.         $data = curl_exec ($ch);
  218.         curl_close ($ch);
  219.  
  220.         preg_match ("/duration=['\"]([0-9]*)['\"]/", $data, $match);
  221.         return $match [1];
  222.  
  223.     } catch (Exception $e) {
  224.         # returning 0 if the YouTube API fails for some reason.
  225.         return '0';
  226.     }
  227. }
  228.  
  229. ?>
clone this paste RAW Paste Data