Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Last active March 17, 2017 22:05
Show Gist options
  • Save tzkmx/4c832432bc63fd67a3a16f940a184145 to your computer and use it in GitHub Desktop.
Save tzkmx/4c832432bc63fd67a3a16f940a184145 to your computer and use it in GitHub Desktop.
Filter function to fix uploads directory (customized WordPress paths)

Moving WordPress to custom subdirectory and customize its managed paths

This is a must-use plugin to fix your uploads paths (URL & directory), for advanced paths customization for your wordpress intallation.

  • WordPress is installed at /wp subdirectory.
//wp-config.php
define('WP_HOME', 'http://example.com');
define('WP_SITEURL', 'http://example.com/wp');
  • WordPress front controller point to that directory
//index.php
/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp/wp-blog-header.php' );
  • Content dir is at /, not subdirectory
define('WP_CONTENT_DIR', dirname(__FILE__) );
define('WP_CONTENT_URL', WP_HOME );
  • Plugins are located in /extensions
define('WP_PLUGIN_DIR', WP_CONTENT_DIR . '/extensions');
define('WP_PLUGIN_URL', WP_HOME . '/extensions');
  • Must use plugins located in /must
define('WPMU_PLUGIN_DIR', WP_CONTENT_DIR . '/must');
define('WPMU_PLUGIN_URL', WP_CONTENT_URL . '/must');
  • Uploads placed in /media
define('UPLOADS', '../media'); // relative to ABSPATH, if you use only "media", it'd be "/wp/media"

However the uploaded files will have a URL like http://example.com/wp/../media/2017/01/media1.jpg

To fix this you place the PHP file into the /must plugins directory.

If you want to put your uploads directory in "/media" (i.e.: http://yoursite.net/media) instead of "wp-content/uploads".

<?php
/**
* @see http://composer.rarst.net/recipe/core-package //define("UPLOADS", "../media");
* @version 0.1
*/
/*
Plugin Name: UploadsToMedia
Plugin URI: https://gist.github.com/tzkmx/4c832432bc63fd67a3a16f940a184145
Description: Fixes paths to media directory
Author: Jesus Franco
Version: 0.1
Author URI: https://tzkmx.wordpress.com/
*/
add_filter( 'upload_dir', function( $uploads_array ) {
$fixed_uploads_array = [];
foreach( $uploads_array as $part => $value ) {
if( in_array( $part, ['path', 'url', 'basedir', 'baseurl'] ) ) {
$fixed_uploads_array[$part] = str_replace('wp/../', '', $value);
} else {
$fixed_uploads_array[$part] = $value;
}
}
return $fixed_uploads_array;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment