How to Define a PHP Constant If It’s Not Already Defined

PHP logo

This is an important practice to get into, especially if you’re developing free and premium versions of your WordPress plugins.

That’s because your users will often already have your free version installed and activated when they attempt to install your premium version. Assuming most of your code overlaps, you may end up with conflicts if your constants aren’t defined carefully.

Consider a typical PHP constant to define your plugin’s directory:

define( 'MY_PLUGIN_DIR', dirname( __FILE__ ) );

Here’s how we can change that so you’ll only define the constant if it hasn’t already been defined:

defined( 'MY_PLUGIN_DIR' ) or define( 'MY_PLUGIN_DIR', dirname( __FILE__ ) );

Happy coding!

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x