There are several ways to add scripts only to certain admin pages. The best option, from my point of view, is to hook into admin_enqueue_scripts
and use the $hook
parameter:
add_action('admin_enqueue_scripts', 'cyb_admin_scripts');
function cyb_admin_scripts( $hook ) {
//You may need adjustment here to match for page
//If the URL of your page is admin.php?page=psbg, the hook
// to check would be toplevel_page_psbg
if( $hook == 'toplevel_page_my-page-slug' ) {
wp_register_script('my-script', plugins_url() . '/my-plugin/js/script.js', array('jquery'));
wp_register_style('my-style', plugins_url() . '/my-plugin/css/style.css');
wp_enqueue_style('my-style');
wp_enqueue_script( 'my-script');
}
}
Other common way I see often is using the load-page action to enqueue the files. For example:
//Adding the menu in admin area
add_action('admin_menu', 'cyb_add_menu');
function cyb_add_menu(){
$hook_suffix = add_menu_page(__('Page title'), __('Menu title'), 'manage_options', 'my-page-slug', 'display_callback_fn');
// Call to cyb_settings_page_load() when our page is loaded
add_action( 'load-'. $hook_suffix, 'cyb_settings_page_load' );
}
function cyb_settings_page_load() {
//Enqueue styles and scripts
wp_enqueue_script('my-script', plugins_url() . '/my-plugin/js/script.js', array('jquery'));
wp_enqueue_style('my-style', plugins_url() . '/my-plugin/css/style.css');
}
function display_callback_fn() {
//Build your page hiere
}