blogger-import-fix.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /*
  3. Plugin Name: blogger-import-fix
  4. Description: <strong>WARNING!</strong> Enabling this plugin will automatically apply fixes on posts imported from Blogger. It will (1) replace images with their highest resolution version; (2) update slug to be same as Blogger; (3) replace Blogger read more anchor link to `&lt;!--more--&gt;` for WordPress. Note: Its success or results may vary. Please do a backup before activating!!
  5. */
  6. /**
  7. * Fixes stuff that are Blogger specific but causes issues on WP.
  8. *
  9. * - Replaces the img tags with bigger image version from their parent `<a>`
  10. * tag.
  11. * - Replaces Blogger's read more tag
  12. */
  13. function fix_blogger_stuff_for_wp( $html ) {
  14. $pattern = array(
  15. // td container is for when there is image caption, otherwise it's div or sometimes without div
  16. '/((?:<(?:div|td)[^>]+>))<a href="(https?:\/\/[^>]+(?:jpg|gif|png))"[^>]+><img alt="([^"]+)"[^>]+><\/a>((?:<\/(?:div|td)>))/U',
  17. '/((?:<(?:div|td)[^>]+>))<a href="(https?:\/\/[^>]+(?:jpg|gif|png))"[^>]+><img[^>]+><\/a>((?:<\/(?:div|td)>))/U',
  18. '/<a name=\'more\'><\/a>/'
  19. );
  20. $replacement = array(
  21. '$1<img src="$2" alt="$3" title="$3"/>$4',
  22. '$1<img src="$2" />$3',
  23. // `<a name='more'></a>` to `<!--more-->` for WordPress
  24. '<!--more-->'
  25. );
  26. $html = preg_replace( $pattern, $replacement, $html );
  27. return $html;
  28. }
  29. /**
  30. * Runs when Activating the plugin.
  31. *
  32. * Activating the plugin everytime runs the fixes. Common sense tells me it
  33. * should be ok to run it over already converted content.
  34. */
  35. function blogger_fix_activate() {
  36. $posts = get_posts( array(
  37. 'posts_per_page' => -1,
  38. ) );
  39. if ( $posts ) {
  40. foreach ( $posts as $post ) :
  41. setup_postdata( $post );
  42. //$content = apply_filters( 'the_content', $post->post_content );
  43. // It will update the post content. So applying `the_content` filter
  44. // to it and then updating content may not be a good idea.
  45. $content = $post->post_content;
  46. // Applies changes for Blogger
  47. $content = fix_blogger_stuff_for_wp($content);
  48. // Update post content
  49. $new_post_data = array(
  50. 'ID' => $post->ID,
  51. 'post_content' => $content,
  52. );
  53. // For fixing slug to be same as Blogger
  54. $permalink = get_post_meta( $post->ID, 'blogger_permalink', true );
  55. if ( ! empty( $permalink ) ) {
  56. $slug = explode("/",$permalink);
  57. $slug = explode(".",$slug[3]);
  58. $slug = $slug[0];
  59. $new_post_data['post_name'] = $slug;
  60. }
  61. wp_update_post( $new_post_data );
  62. endforeach;
  63. wp_reset_postdata();
  64. }
  65. }
  66. register_activation_hook( __FILE__, 'blogger_fix_activate' );