beans_path_to_url

Convert internal path to a url.

This function must only be used with internal paths.

beans_path_to_url( string $path )

Return: (string) Url.

Parameters

NameTypeRequiredDefaultDescription
$pathstringtrue-Path to be converted. Accepts absolute and relative internal paths.

Source

function beans_path_to_url( $path ) {

	static $root, $host;

	// Stop here if it is already a url or data format.
	if ( true == preg_match( '#^(http|https|\/\/|data)#', $path ) ) {
		return $path;
	}

	// Standardize backslashes.
	$path = wp_normalize_path( $path );

	// Set root and host if it isn't cached.
	if ( ! $root ) {

		// Standardize backslashes set host.
		$root = wp_normalize_path( untrailingslashit( ABSPATH ) );
		$host = untrailingslashit( site_url() );

		// Remove subfolder if necessary.
		if ( '' !== ( $subfolder = parse_url( $host, PHP_URL_PATH ) ) ) {

			$root = preg_replace( '#' . untrailingslashit( preg_quote( $subfolder ) ) . '$#', '', $root );
			$host = preg_replace( '#' . untrailingslashit( preg_quote( $subfolder ) ) . '$#', '', $host );

			// Add the blog path for multsites.
			if ( ! is_main_site() && ( $blogdetails = get_blog_details( get_current_blog_id() ) ) ) {
				if ( ! ( defined( 'WP_SITEURL' ) ) || ( defined( 'WP_SITEURL' ) && WP_SITEURL == site_url() ) ) {
					$host = untrailingslashit( $host ) . $blogdetails->path;
				}
			}
		}

		$explode = beans_get( 0, explode( '/' , trailingslashit( ltrim( $subfolder, '/' ) ) ) );

		// Maybe re-add tilde from host.
		if ( false !== stripos( $explode, '~' ) ) {
			$host = trailingslashit( $host ) . $explode;
		}
	}

	// Remove root if necessary.
	if ( false !== stripos( $path, $root ) ) {
		$path = str_replace( $root, '', $path );
	} elseif ( false !== stripos( $path, beans_get( 'DOCUMENT_ROOT', $_SERVER ) ) ) {
		$path = str_replace( beans_get( 'DOCUMENT_ROOT', $_SERVER ), '', $path );
	}

	return trailingslashit( $host ) . ltrim( $path, '/' );

}