Mode

While developing a website, I often have to switch back and forth between different builds. Instead of manually rewriting the scripts and styles that load into the site between builds, I started using a function determine which state the sites is in and load the JavaScript and CSS conditionally.

I include a custom theme settings page in the admin to set an option for the mode state. I set two options: development or production. I include a toggle switch on the front end of the site so that I don’t have to navigate to those options to switch it back and forth.

header.php
<ul class="build navbar-nav me-auto">
  <li class="nav-item form-check form-switch form-switch-md">
    <?php dwp23_front_production_toggle();?>
    <form id="theme_production_toggle" name="theme_production_toggle" action="" method="post">
      <?php wp_nonce_field('update-options','theme_front_end'); ?>
      <input type="hidden" name="action" value="0">
      <input type="checkbox" name="action" value="1" class="form-check-input" onChange="this.form.submit()" <?php checked( '1', get_option( 'theme_production' ) ); ?> >
      <label class="mt-1 form-check-label" for="dev-toggle"><span class="state text-muted">mode -dev</span></label>
    </form>
  </li>
</ul>
inc/dwp-dev.php
/***********************************************************
##################### Theme Mode ###########################
************************************************************/

add_action( 'wp_enqueue_scripts', 'dwp23_dwp23_theme_mode_enqueue', 100 );
function dwp23_dwp23_theme_mode_enqueue() {
  $dwp23_theme_mode_setting = get_option('dwp23_theme_mode');
  if( $dwp23_theme_mode_setting !== '1' ) {
    wp_deregister_style('sass');
    wp_deregister_style('icons');
    wp_deregister_style('style');
    wp_enqueue_style('style-min', get_template_directory_uri() . '/css/style.min.css');
  }
}

add_action('admin_post_dwp23_theme_mode_toggle', 'dwp23_production_toggle');
function dwp23_production_toggle() {
  $production_setting = $_POST['dwp23_theme_mode_toggle'] ? $_POST['dwp23_theme_mode_toggle'] : '';
  if(current_user_can('manage_options') && wp_verify_nonce('dwp23_theme_mode_toggle'))  {
    update_option('dwp23_theme_mode', esc_html($production_setting));
  }
  else {
    error_log( "DIE!" );
    die("DIE");
  }
}

function dwp23_front_production_toggle() {
  if (isset($_POST['action'])) {
    if (current_user_can('manage_options') && wp_verify_nonce($_POST['theme_front_end'],'update-options')){
      update_option('dwp23_theme_mode',$_POST['action']);
    } else {
      error_log( "DIE!" );
      die("DIE");
    }
  }
}