Created
October 16, 2018 10:04
-
-
Save seebz/791ab99b7ba72a3ed8a12a87475ed3eb to your computer and use it in GitHub Desktop.
Pretty URI - Enhance internal URIs (usefull when a migration is planned).
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: Pretty URI | |
Description: Enhance internal URIs (usefull when a migration is planned). | |
Version: 1.0 | |
Author: Seebz | |
Author URI: http://seebz.net/ | |
*/ | |
// Is WP on server root ? | |
if ( ! pu_is_wp_on_root() ) { | |
return; | |
} | |
/* | |
* Filters | |
*/ | |
// Post content/excerpt (on save) | |
add_filter( 'content_save_pre', 'pu_filter_post_content' ); | |
add_filter( 'excerpt_save_pre', 'pu_filter_post_content' ); | |
function pu_filter_post_content( $content ) { | |
$content = pu_replace_links_uri( $content ); | |
$content = pu_replace_images_uri( $content ); | |
return $content; | |
} | |
// Menu items (on display) | |
add_filter( 'wp_nav_menu_items', 'pu_filter_menu_items' ); | |
function pu_filter_menu_items( $items ) { | |
$items = pu_replace_links_uri( $items ); | |
return $items; | |
} | |
// Attachment URL | |
add_filter( 'wp_get_attachment_url', 'pu_filter_attachment_url' ); | |
function pu_filter_attachment_url( $url ) { | |
$url = pu_replace_content_uri( $url ); | |
return $url; | |
} | |
/* | |
* Utility | |
*/ | |
// Is WP installed on server root | |
function pu_is_wp_on_root() { | |
$wp_url = get_site_url(); | |
$wp_path = parse_url( $wp_url, PHP_URL_PATH ); | |
return ( ! $wp_path || $wp_path == '/' ); | |
} | |
// Replace URIs in links (<a>) | |
function pu_replace_links_uri( $content ) { | |
$pattern = '`<a[^>]*>`'; | |
if ( preg_match_all( $pattern, $content, $matches ) ) { | |
foreach( $matches[0] as $m ) { | |
$content = str_replace( $m, pu_replace_content_uri( $m ), $content ); | |
} | |
} | |
return $content; | |
} | |
// Replace URIs in images (<img>) | |
function pu_replace_images_uri( $content ) { | |
$pattern = '`<img[^>]*>`'; | |
if ( preg_match_all( $pattern, $content, $matches ) ) { | |
foreach( $matches[0] as $m ) { | |
$content = str_replace( $m, pu_replace_content_uri( $m ), $content ); | |
} | |
} | |
return $content; | |
} | |
// Replace URIs in content | |
function pu_replace_content_uri( $content ) { | |
$search = get_site_url( null, '/' ); | |
$replace = '/'; | |
return str_replace( $search, $replace, $content ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment