Created
August 29, 2011 22:14
-
-
Save chrisguitarguy/1179555 to your computer and use it in GitHub Desktop.
Adds a custom shortlink structure to WordPress
This file contains 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 | |
/* | |
Plugin Name: WP Custom Shortlinks | |
Plugin URI: http://pmg.co/ | |
Description: Customizes the default WordPress Shortlinks | |
Version: n/a | |
Author: Christopher Davis | |
Author URI: http://pmg.co/people/chris | |
*/ | |
register_activation_hook( __FILE__, 'wpse26869_activation' ); | |
function wpse26869_activation() | |
{ | |
wpse26869_add_rewrites(); | |
flush_rewrite_rules(); | |
} | |
add_action( 'init', 'wpse26869_add_rewrites' ); | |
function wpse26869_add_rewrites() | |
{ | |
add_rewrite_rule( '^s/(\d+)$', 'index.php?short=$matches[1]', 'top' ); | |
} | |
add_filter( 'query_vars', 'wpse26869_query_vars', 10, 1 ); | |
function wpse26869_query_vars( $vars ) | |
{ | |
$vars[] = 'short'; | |
return $vars; | |
} | |
add_action( 'template_redirect', 'wpse26869_shortlink_redirect' ); | |
function wpse26869_shortlink_redirect() | |
{ | |
// bail if this isn't a short link | |
if( ! get_query_var( 'short' ) ) return; | |
global $wp_query; | |
$id = absint( get_query_var( 'short' ) ); | |
if( ! $id ) | |
{ | |
$wp_query->is_404 = true; | |
return; | |
} | |
$link = get_permalink( $id ); | |
if( ! $link ) | |
{ | |
$wp_query->is_404 = true; | |
return; | |
} | |
wp_redirect( esc_url( $link ), 301 ); | |
exit(); | |
} | |
add_filter( 'get_shortlink', 'wpse26869_get_shortlink', 10, 3 ); | |
function wpse26869_get_shortlink( $link, $id, $context ) | |
{ | |
if( 'query' == $context && is_single() ) | |
{ | |
$id = get_queried_object_id(); | |
} | |
return home_url( 's/' . $id ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment