How to include a file for admin and 2 pages without being loaded on other parts of the site?

Include the right way

There are two different things to remember when including a file:

1. Use a core function to get the path

I explained most of the available functions with this answer. Consider to take a look at the /wp-includes/link-template.php file in core to see what else core has got for you.

Resources

Php is pretty cheap when it comes to loading files: It doesn’t matter as long as you don’t execute functions. So: Loading the file won’t be a problem. Loading the class itself (and maybe running a __construct(); on window load) may become extensive. So the only real Q is: How to avoid executing your whole process on specifc pages.

2.1. Use the right hooks

When using one of the add_submenu/menu/*_page() functions, then you can take the @return value and use it to determine the hook for the current page.

// Example:
$hook_suffix = add_options_page( 
    'My Plugin Options', 
    'My Plugin', 
    'required_capability', 
    'my-unique-identifier', 
    'my_plugin_options' 
);
// Add hook for action executed when plugin's options page is loaded
add_action( "load-{$hook_suffix}" , 'my_load_function' );

2.2. Or check the right globals

You got a whole load of globals available to admin screens. Most are already set on init or admin_init hooks.

  • $menu
  • $submenu
  • $pagenow
  • $typenow
  • $self
  • $parent_file
  • $submenu_file
  • etc. …

You can also check what’s inside the global $current_screen. This offers an object where you can check against it’s parts.

Globals vs. public API

$_GLOBALS are nothing that gets saved into the DB. So it’s only available as long as it’s registered before. Point is that you can’t exclude a class, but still have the global available. In any way, you’ll have to rethink the concept: You can do a lot of stuff to globals like unset, etc. Most of this is something you don’t want to happen. If you’re offering your users (and yourself) a public API then it’s up to you, what those functions can do or not.

In my opinion it’s easier to add another file that holds you public API. There you can simply include your plugins core files and then call only those functions inside your class that you want to have access too. Another benefit is that you can add predefined arguments. Those allow you work faster in your templates but also get wp_parse_args( $defaults, $input_args ); with your default class vars.

Activation, Deactivation, Uninstall…

…did I already explain in detail with this answer.