I'm writing a WordPress plugin. At the top of the plugin file, I define some constants. Can I leave out the if ( ! defined( 'THE_CONSTANT' ) ) tests?

Some other plugins that I've studied includes such if ( ! defined tests, some don't. Personally, I don't know why my plugin file would ever be included twice?

The reason I don't want to include if ( ! defined ... is that I think this is hard to read:
(XYZABC would be the plugin name)

if ( ! defined( 'XYZABC_PLUGIN_BASENAME' ) )
    define( 'XYZABC_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
if ( ! defined( 'XYZABC_SETTINGS_SLUG' ) )
    define( 'XYZABC_SETTINGS_SLUG', 'xyzabc_comments_options' );
if ( ! defined( 'XYZABC_ENABLED_QUERY_PARAM' ) )
    define( 'XYZABC_ENABLED_QUERY_PARAM', 'xyzabc-comments-enabled' );

But this is relatively nice to read:

define( 'XYZABC_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
define( 'XYZABC_SETTINGS_SLUG', 'xyzabc_comments_options' );
define( 'XYZABC_ENABLED_QUERY_PARAM', 'xyzabc-comments-enabled' );

I defined this function, and then the duplicated-constant-name issue is mostly gone.

function myplugin_define_default($constant_name, $value) {
    if (! defined($constant_name))
        define($constant_name, $value);

So now my code looks like so:

define( 'XYZABC_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
xyzabc_define_default( 'XYZABC_SETTINGS_SLUG', 'xyzabc_comments_options' );
xyzabc_define_default( 'XYZABC_ENABLED_QUERY_PARAM', 'xyzabc-comments-enabled' );

By doing the !defined() check you allow earlier code to define that constant before you. This could be useful, for example, if a user is allowed to define its own values for some constants in a file like wp-config.php.

As for code readability, you may consider using the following one-liner, although you could put a regular if on a single line as well.

defined('XYZABC_PLUGIN_BASENAME') or define('XYZABC_PLUGIN_BASENAME', 'your_value');
  • Okay, thanks, didn't know that people sometimes defined plugin constants in wp-config.php. I suppose people do that, if the plugin Settings page isn't flexible enough. — Perhaps I'll keep if ( ! defined sometimes then — I can think of some weird cases when people might want to redefined some of the constants. – KajMagnus Jun 17 '12 at 7:36
  • Your defined ... or define is more readable than the if ( ! defined ... version, I think. – KajMagnus Jun 17 '12 at 7:38
  • I added a perhaps even more readable version in my original post. – KajMagnus Jun 17 '12 at 7:52
  • 1
    Wrapping it in a function is possible. Note that even though your code may look prettier, people who are reading it will need to look up your custom function first. Not a big deal, but I’d prefer sticking to native define functions here. – Geert Jun 17 '12 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.