cliffordp
6/21/2016 - 2:46 PM

Example of an add-on with Freemius that is activated only when the parent plugin is activated and loaded.

Example of an add-on with Freemius that is activated only when the parent plugin is activated and loaded.

<?php
	/*
	Plugin Name:	My Add-on
	Version:		1.0.0
	Author:			Vova Feldman
	Author URI:		http://freemius.com
	License:		GPL2
	*/
	
	// Exit if accessed directly
	if ( ! defined( 'ABSPATH' ) ) {
		exit;
	}

	class My_Addon
	{
		static function init ()
		{
			register_activation_hook( __FILE__, array( __CLASS__, '_install' ) );

			if ( ! self::_is_parent_active_and_loaded() ) {
				return;
			}

			self::init_freemius();
		}

		#region Parent Plugin Check

		/**
		 * Check if parent plugin is activated (not necessarly loaded).
		 *
		 * @author Vova Feldman (@svovaf)
		 *
		 * @return bool
		 */
		static function _is_parent_activated()
		{
			$active_plugins_basenames = get_option( 'active_plugins' );
			foreach ( $active_plugins_basenames as $plugin_basename ) {
				if ( false !== strpos( $plugin_basename, '/my-plugin-main-file.php' ) ) {
					return true;
				}
			}

			return false;
		}

		/**
		 * Check if parent plugin is active and loaded.
		 *
		 * @author Vova Feldman (@svovaf)
		 *
		 * @return bool
		 */
		static function _is_parent_active_and_loaded()
		{
			return class_exists( 'My_Plugin' );
		}

		/**
		 *
		 * @author Vova Feldman (@svovaf)
		 */
		static function _install()
		{
			if ( ! self::_is_parent_active_and_loaded() ) {
				deactivate_plugins( basename( __FILE__ ) );

				// Message error + allow back link.
				wp_die( __( 'My Add-on requires My Plugin to be installed and activated.' ), __( 'Error' ), array( 'back_link' => true ) );
			}
		}

		private static function init_freemius()
		{
			global $my_fs;

			if ( ! isset( $my_fs ) ) {
				// Since we are making sure that parent plugin is loaded first with FS, Freemius should already be loaded.
				$my_fs = fs_dynamic_init( array(
					'id'                => '1234',
					'slug'              => 'my-plugin-slug',
					'public_key'        => 'pk_my_addon_public_key',
					'is_premium'        => true,
					'parent'      => array(
						'id'         => '123',
						'slug'       => 'my-plugin-slug',
						'public_key' => 'pk_my_plugin_public_key',
						'name'       => 'My Plugin',
					),
				) );
			}
		}

		#endregion Parent Plugin Check
	}

	if (My_Addon::_is_parent_active_and_loaded())
	{
		// If parent plugin already included, init add-on.
		My_Addon::init();
	}
	else if (My_Addon::_is_parent_activated())
	{
		// Init add-on only after the parent plugins is loaded.
		add_action( 'my_plugin_loaded', array( __CLASS__, 'init' ) );
	}
	else
	{
		// Even though the parent plugin is not activated, execute add-on for activation / uninstall hooks.
		My_Addon::init();
	}
?>