Here’s my bare-bones template that I use when creating a plugin with OOP. Feel free to modify to your liking.
Template
if ( !defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
if ( !class_exists( 'MyPluginName' ) ) {
class MyPluginName {
public function __construct() { // Call your actions/filters here
add_action( 'tag', array( $this, 'plgn_abbr_function' ), 10, 1 );
}
// Begin functions here
public function plgn_abbr_function() {
# Code here...
}
}
}
if ( class_exists( 'MyPluginName' ) ) { // Instantiate the plugin class
global $plgn_abbr;
$plgn_abbr = new MyPluginName();
}
A few things I immediately noticed from skimming through your attempts:
- You’d want to call your
add_actions
under the__construct()
and have your functions places outside of that but you’ll need to change the layout of it as well. -
You need to update how your
add_action
layoutadd_action( 'admin_notices', 'show_notice', 100 );
This structure will not work when utilizing a
class
, it should be:add_action( 'admin_notices', array( $this, 'show_notice' ), 100 );
-
You’d need to append
public
before all of your functions like so:public function your_code()
Solution
Here’s an update to your code utilizing the template that I gave you above, it’s been tested and works on my end:
if ( !defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
if ( !class_exists( 'MyPluginName' ) ) {
class MyPluginName {
public function __construct() {
// check for required php version and deactivate the plugin if php version is less.
if ( version_compare( PHP_VERSION, '5.4', '<' ) ) {
add_action( 'admin_notices', array( $this, 'show_notice' ), 100 );
add_action( 'admin_init', array( $this, 'MyPluginName_deactivate_self' ) );
return;
}
}
public function show_notice() {
?>
<div class="error">
<p><?php echo 'MyPluginName requires minimum PHP 5.4 to function properly. Please upgrade PHP version. The Plugin has been auto-deactivated.. You have PHP version '.PHP_VERSION; ?></p>
</div>
<?php
if ( isset( $_GET['activate'] ) ) {
unset( $_GET['activate'] );
}
}
public function MyPluginName_deactivate_self() {
deactivate_plugins( plugin_basename( __FILE__ ) );
}
}
}
if ( class_exists( 'MyPluginName' ) ) { // Instantiate the plugin class
global $plgn_abbr;
$plgn_abbr = new MyPluginName();
}