Skip to content

Instantly share code, notes, and snippets.

@cliffordp
Forked from vovafeldman/fs-my-addon.php
Created June 21, 2016 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cliffordp/d1c8b41225fbcef1534d42372fdb17ef to your computer and use it in GitHub Desktop.
Save cliffordp/d1c8b41225fbcef1534d42372fdb17ef to your computer and use it in GitHub Desktop.
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();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment