2

I'm developing my first WordPress plugin. I need to use a custom CSS for the settings pages that I created for the plugin but when I enqueue my stylesheet file, it affects the whole WordPress backend and not just my plugin's settings page. Is possible to solve this problem? How?

1 Answer 1

5

When you want to add styles or scripts in WordPress you enqueue them using hooks. For the admin side the hook you are looking for is called admin_enqueue_scripts.

You can add something like

/**
 * Register and enqueue a custom stylesheet in the WordPress admin.
 */
function wpdocs_enqueue_custom_admin_style() {
        wp_register_style( 'custom_wp_admin_css', plugin_dir_url( __FILE__ ) . 'css/woo-solo-api-admin.css', false, '1.0.0' );
        wp_enqueue_style( 'custom_wp_admin_css' );
}

add_action( 'admin_enqueue_scripts', 'wpdocs_enqueue_custom_admin_style' ); 

You just need to be careful to correctly specify the url of the css script you want to enqueue.

Hope this helps.

Oh and https://developer.wordpress.org page is great for finding out about WordPress functionality, core functions, hooks etc.

Also check out the plugin handbook: https://developer.wordpress.org/plugins/ Loads of useful information can be found there :)

EDIT:

admin_enqueue_scripts has a parameter you can use read more

/**
 * Register and enqueue a custom stylesheet in the WordPress admin.
 */
function wpdocs_enqueue_custom_admin_style( $hook ) {
    if ( $hook === 'edit.php' ) {
        wp_register_style( 'custom_wp_admin_css', plugin_dir_url( __FILE__ ) . 'css/woo-solo-api-admin.css', false, '1.0.0' );
        wp_enqueue_style( 'custom_wp_admin_css' );        
    }
}

add_action( 'admin_enqueue_scripts', 'wpdocs_enqueue_custom_admin_style' ); 

This will load the script only on the edit post screen.

You can see what hook is loaded on your screen by adding

error_log( print_r( $hook, true ) );

In your wpdocs_enqueue_custom_admin_style function before the condition. Enable the debug log in your wp-config.php and you'll get a name of your custom post screen hook.

Alternatively, you could target the $current_screen to match the CPT's screen. This will load the script only on that page.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for reply but I know I must use admin_enqueue_scripts hook and wp_enqueue_style function but the problem is that doing this my CSS style affects whole admin side not my plugin settings pages only. E.g.: if in my CSS I write h1 { color: red; } every h1 tag shows in red and not just the h1 tags in my plugin pages...
As noted in the docs, you can pass a $hook argument and then see on what page you want your script to load :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.