Daniel Dvorkin

My take on WordPress and related geekery

mu-plugins, maybe.

UPDATED: Added also deactivation enforcing

A few days ago, Ryan McCue on twitter asked a question that I’ve asked myself a few times now, and always deferred looking for an answer and moved away to do more pressing things. But this time I really needed a solution for a site we’re doing, and came up with an idea.

I don’t really like moving everything to mu-plugins because:

a) You can’t deactivate on dev for testing things.
b) It’s stupid, but I like having an unified list of plugins. People never check the “must-use” tab when looking for activated plugins.

So, wouldn’t it be neat to have mu-plugins on production that work like standard plugins in dev and staging?

I came up with this mu-plugin:

<?php
/*
Plugin Name:	Force Plugin Activation/Deactivation (except if WP_DEBUG is on)
Plugin URI: 	http://danieldvork.in
Description:	Make sure the required plugins are always active.
Version:    	1.0
Author:     	Daniel Dvorkin
Author URI: 	http://danieldvork.in
*/

class Force_Plugin_Activation {

	private $force_active = array(
		'advanced-custom-fields/acf.php',
		'acf-repeater/acf-repeater.php',
		'acf-options-page/acf-options-page.php',
		'wp-git-deploy/git-deployment.php',
		'posts-to-posts/posts-to-posts.php'
	);

	private $force_deactive = array(
		'debug-bar/debug-bar.php',
	);


	function __construct() {
		add_filter( 'option_active_plugins',    array( $this, 'force_plugins'       ), 10, 1 );
		add_filter( 'plugin_action_links',      array( $this, 'plugin_action_links' ), 99, 4 );
	}

	function force_plugins( $plugins ) {

		$plugins = array_merge( (array) $plugins, $this->force_active   );
		$plugins = array_diff ( (array) $plugins, $this->force_deactive );

		$plugins = array_unique( $plugins );

		return $plugins;
	}

	function plugin_action_links( $actions, $plugin_file, $plugin_data, $context ) {

		if ( in_array( $plugin_file, $this->force_active ) )
			unset( $actions['deactivate'] );

		if ( in_array( $plugin_file, $this->force_deactive ) )
			unset( $actions['activate'] );


		return $actions;
	}
}

// We want to enfornce only on production, where WP_DEBUG is off.
if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
	new Force_Plugin_Activation();
}


End result:

What do you think?

Previous

The Humble Programmer

Next

do_accordion_sections

2 Comments

  1. Hmm,
    Don’t check for plugin existence and activation based on file/folder combo. Check for the class or a function. Users sometimes rename the folders of plugins.

    • This is for services projects I run. User doesn’t even have a way of renaming a folder. What I want to make sure if they can’t deactivate them. Also, you can’t programmatically activate a plugin using a class, you need the path.

Leave a Reply to Chris Christoff Cancel reply

Powered by WordPress & Theme by Anders Norén