Last active
March 11, 2017 11:07
-
-
Save zacscott/970ffebc0bfb960b79b8b9eaa49f6d6e to your computer and use it in GitHub Desktop.
Converts all links in post content, attachments etc. to root relative. This is specifically designed to work well with RAMP
This file contains hidden or 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: Relative URLs | |
* Description: Converts all links in post content, attachments etc. to root | |
* relative. This is specifically designed to work well with | |
* <a href="https://crowdfavorite.com/ramp/">RAMP</a>. | |
* Version: 1.1 | |
* Author: Zachary Scott | |
*/ | |
namespace zacscott; | |
/** | |
* Relative links plugin driver class. | |
* | |
* @author Zachary Scott <[email protected]> | |
*/ | |
class RelativeLinksPlugin { | |
function __construct() { | |
add_filter( 'content_save_pre', array( $this, 'make_root_relative' ) ); | |
} | |
// Makes all of the URLs in the given string root relative for the current site | |
function make_root_relative( $string ) { | |
assert( is_string( $string ) ); | |
// The site URLs to trim | |
$site_urls = array( home_url(), ); | |
$site_urls = apply_filters( 'relative_urls_list', $site_urls ); | |
// Trim each of the site URLs in hte given content | |
foreach ( $site_urls as $site_url ) { | |
// Remove the path from the url | |
$url_bits = parse_url( $site_url ); | |
$url_bits['path'] = ''; | |
// Make URL relative in string content (for both http & https) | |
foreach ( array( 'http', 'https' ) as $scheme ) { | |
$url_bits['scheme'] = $scheme; | |
$site_url = $this->unparse_url( $url_bits ); | |
$string = str_replace( $site_url, '', $string ); | |
} | |
} | |
return $string; | |
} | |
// Unparses a URL generated by `parse_url()` | |
// based off this - http://php.net/manual/en/function.parse-url.php#106731 | |
function unparse_url( $parsed_url ) { | |
assert( ! empty( $parsed_url ) ); | |
$scheme = isset( $parsed_url['scheme'] ) ? $parsed_url['scheme'] . '://' : ''; | |
$host = isset( $parsed_url['host'] ) ? $parsed_url['host'] : ''; | |
$port = isset( $parsed_url['port'] ) ? ':' . $parsed_url['port'] : ''; | |
$user = isset( $parsed_url['user'] ) ? $parsed_url['user'] : ''; | |
$pass = isset( $parsed_url['pass'] ) ? ':' . $parsed_url['pass'] : ''; | |
$pass = ( $user || $pass ) ? "$pass@" : ''; | |
$path = isset( $parsed_url['path'] ) ? $parsed_url['path'] : ''; | |
$query = isset( $parsed_url['query'] ) ? '?' . $parsed_url['query'] : ''; | |
$fragment = isset( $parsed_url['fragment'] ) ? '#' . $parsed_url['fragment'] : ''; | |
return "$scheme$user$pass$host$port$path$query$fragment"; | |
} | |
} | |
// Boot | |
new RelativeLinksPlugin(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment