Where should I use get_option in a plugin

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!

Read More
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!

Related posts

Leave a Reply

1 comment

  1. 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 );