shortlinks.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * Module Name: WP.me Shortlinks
  4. * Module Description: Create short and simple links for all posts and pages.
  5. * Sort Order: 8
  6. * First Introduced: 1.1
  7. * Requires Connection: Yes
  8. * Auto Activate: Yes
  9. * Module Tags: Social
  10. * Feature: Writing
  11. * Additional Search Queries: shortlinks, wp.me
  12. */
  13. add_filter( 'pre_get_shortlink', 'wpme_get_shortlink_handler', 1, 4 );
  14. if ( !function_exists( 'wpme_dec2sixtwo' ) ) {
  15. function wpme_dec2sixtwo( $num ) {
  16. $index = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  17. $out = "";
  18. if ( $num < 0 ) {
  19. $out = '-';
  20. $num = abs( $num );
  21. }
  22. for ( $t = floor( log10( $num ) / log10( 62 ) ); $t >= 0; $t-- ) {
  23. $a = floor( $num / pow( 62, $t ) );
  24. $out = $out . substr( $index, $a, 1 );
  25. $num = $num - ( $a * pow( 62, $t ) );
  26. }
  27. return $out;
  28. }
  29. }
  30. function wpme_get_shortlink( $id = 0, $context = 'post', $allow_slugs = true ) {
  31. global $wp_query;
  32. $blog_id = Jetpack_Options::get_option( 'id' );
  33. if ( 'query' == $context ) {
  34. if ( is_singular() ) {
  35. $id = $wp_query->get_queried_object_id();
  36. $context = 'post';
  37. } elseif ( is_front_page() ) {
  38. $context = 'blog';
  39. } else {
  40. return '';
  41. }
  42. }
  43. if ( 'blog' == $context ) {
  44. if ( empty( $id ) )
  45. $id = $blog_id;
  46. $wpme_url = 'http://wp.me/' . wpme_dec2sixtwo( $id );
  47. return set_url_scheme( $wpme_url );
  48. }
  49. $post = get_post( $id );
  50. if ( empty( $post ) )
  51. return '';
  52. $post_id = $post->ID;
  53. $type = '';
  54. if ( $allow_slugs && 'publish' == $post->post_status && 'post' == $post->post_type && strlen( $post->post_name ) <= 8 && false === strpos( $post->post_name, '%' )
  55. && false === strpos( $post->post_name, '-' ) ) {
  56. $id = $post->post_name;
  57. $type = 's';
  58. } else {
  59. $id = wpme_dec2sixtwo( $post_id );
  60. if ( 'page' == $post->post_type )
  61. $type = 'P';
  62. elseif ( 'post' == $post->post_type || post_type_supports( $post->post_type, 'shortlinks' ) )
  63. $type= 'p';
  64. elseif ( 'attachment' == $post->post_type )
  65. $type = 'a';
  66. }
  67. if ( empty( $type ) )
  68. return '';
  69. $url = 'http://wp.me/' . $type . wpme_dec2sixtwo( $blog_id ) . '-' . $id;
  70. return set_url_scheme( $url );
  71. }
  72. function wpme_get_shortlink_handler( $shortlink, $id, $context, $allow_slugs ) {
  73. return wpme_get_shortlink( $id, $context, $allow_slugs );
  74. }