Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am working on creating a plugin to help me with future development projects. I want to make sure what I am using best practices when I write it. My question is about the use of get_option in my plugin.

I have setup an options page for the plugin and have set a couple options there. Is it better to check the option on the add_action step or with the function that is being added. I have written up a short example to help illustrate my question. Thanks!

if ( get_option('my_option[option_1]') ==='1' ) {
  add_action('init', 'my_action')
}

or

add_action('init', 'my_action');
function my_action() {
  if ( get_option('my_option[option_1]') ==='1' ) {
    //do stuff here
  }

My thoughts are that if I check get_option first then I can set it as a var in my plugin and then just check the var anytime I need it. But as I said I am new to plugin development so I don't fully understand the best way to use get_option.

Thanks!

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

Both ways are almost equal, the first will be slightly faster, because the callback is called only if the check equals to TRUE.

Note you cannot test an option like this, unless the option name is really 'my_option[option_1]'. What you probably want is:

if ( $test = get_option('my_option') and 1 === $test['option_1'] )
    add_action();

An extended example:

$my_options = get_option('my_option');

if ( 1 === $my_options['test_1'] )
    add_action( 'init', 'my_init' );

if ( 1 === $my_options['test_2'] )
    add_action( 'shutdown', 'my_shutdown' );

// clean up
unset( $my_options );
share|improve this answer
    
Great, thanks for the help! So based on your update could I set $test to the options array at the top of my plugin and check against it for all the options as I need them? –  yoxalld Jan 9 '13 at 16:37
    
@yoxalld See my update. –  toscho Jan 9 '13 at 16:44
    
That's great! Thank you so much for the help! –  yoxalld Jan 9 '13 at 16:46
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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