Site icon Bytefreaks.net

WordPress: How to disable a plugin on all pages except for a specific one

Advertisements

A few days ago we were struggling to find a way to limit the amount of plugins that load at any point on a WordPress website. We noticed that several plugins enqueue their scripts and their styles in all requests to the website even if they are actually used on a single page only. This issue was important to address as it was making the whole server slower by giving it extra requests from the client that would never provide any actual benefit to the user.

Initially, we tried to selectively enable those plugins on their respective pages but we did not get it right and things would load out of order and break. Instead of following the ‘enable when needed‘ methodology we decided to follow the ‘disable unless needed‘ methodology which seemed simpler at the time.

Our changes involved in adding the following code in the functions.php file of our child theme.

//Register a filter at the correct event
add_filter( 'option_active_plugins', 'bf_plugin_control' );

function bf_plugin_control($plugins) {
  // If we are in the admin area do not touch anything
  if (is_admin()) {
    return $plugins;
  }
  
  // Check if we are at the expected page, if not remove the plugin from the active plugins list
  if(is_page("csv-to-kml-cell-site-map") === FALSE){ 
    // Finding the plugin in the active plugins list
    $key = array_search( 'csv-kml/index.php' , $plugins );
    if ( false !== $key ) {
      // Removing the plugin and dequeuing its scripts
      unset( $plugins[$key] );
      wp_dequeue_script( 'bf_csv_kml_script' );
    }
  }

  if(is_page("random-password-generator") === FALSE){ 
    $key = array_search( 'bytefreaks-password-generator/passwordGenerator.php' , $plugins );
    if ( false !== $key ) {
      unset( $plugins[$key] );
    }
  }
  
  if(is_page("xml-tree-visualizer") === FALSE){ 
    $key = array_search( 'xmltree/xml-tree.php' , $plugins );
    if ( false !== $key ) {
      unset( $plugins[$key] );
      wp_dequeue_script( 'bf_xml_namespace' );
      wp_dequeue_style( 'bf_xml_namespace' );
    }
  }

  return $plugins;
}

One day, we will clean the above code to make it tidy and reusable.. one day, that day is not today.

What the code above does is the following:

This post is also available in: Greek

Exit mobile version