A great many moons ago, I handled my per-site MU plugins in a very straight forward way. I made a halfelf-functions.php
file and checked for the blog ID with if ( $blog_id == 2 ) {...}
and off I went.
Now? I do this:
global $blog_id; $helf_site_url = parse_url( get_site_url( $blog_id ) ); $helf_file = plugin_dir_path( __FILE__ ) .'functions/'. $helf_site_url['host'] .'.php'; if ( file_exists( $helf_file ) ) { include_once( $helf_file ); }
I have a folder called ‘functions’ and in there I have a file for every site that needs it’s own functions. This also let me clean up some rather old code I wasn’t using anymore, but it also let me add in code to include local CSS. Since I version control my mu-plugins
folder, this allowed me to move my custom CSS from Jetpack to a normal CSS file.
Why did I need to do that? Jetpack CSS doesn’t allow the fill param for CSS. Their current justification is that it’s advanced enough that people should be editing the theme. And mine is “But … why?” SVGs are becoming more and more popular, after all, and a number of plugins are allowing them. That means to style your SVGs, you’ll want to use CSS. And you can’t with Jetpack, which means you’re back to the old hell of editing your theme’s CSS. And that was something I wanted to avoid.
You’d think I could do this:
$helf_file_css = plugin_dir_path( __FILE__ ) .'functions/css/'. $helf_site_url['host'] .'.css'; function helf_scripts() { if ( file_exists( $helf_file_css ) ) { wp_enqueue_style( $helf_site_url['host'], $helf_file_css ); } } add_action( 'wp_enqueue_scripts', 'helf_scripts' );
But that actually didn’t work. No matter what I did, the result of $helf_site_url['host']
was empty. I know, right? What’s up with that.
What’s up is me not thinking about how functions ‘know’ what they know.
function helf_scripts() { global $blog_id; $url = parse_url( get_site_url( $blog_id ) ); $css_path = plugin_dir_path( __FILE__ ) .'functions/css/'. $url['host'] .'.css'; $css_url = plugins_url( 'functions/css/'. $url['host'] .'.css', __FILE__ ); if ( file_exists( $css_path ) ) { wp_enqueue_style( $url['host'] , $css_url ); } } add_action( 'wp_enqueue_scripts', 'helf_scripts' );
Inside the function, you see, it can’t see non-globals. So it wouldn’t work. If you’re not using Multisite, you don’t need to use $blog_id
, but I don’t know why you’d want to use this if you weren’t using Multisite. The other silly moment was remembering that plugin_dir_path()
would give me /home/user/public_html/wp-content/mu-plugins
which would make the URL a relative URL, and not at all what I wanted. But using plugins_url()
would give me an absolute path.
Perfect.
Comments
One response to “Per-Site MU Plugins”
Don’t use the $blog_id global, use the
get_current_blog_id()
function instead:https://codex.wordpress.org/Function_Reference/get_current_blog_id