WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Adding CSS/JS Links to Admin Head (2 posts)

  1. AK Ted
    Member
    Posted 1 year ago #

    I'm learning how to add menus to the admin page, i.e., for plugin/theme options pages. What would be the proper way to inject a

    <link rel="stylesheet" type="text/css" href="view.css" media="all">

    into the <head>, but only when my custom menu is selected?

    This is what I use to create the menu:

    add_action('admin_menu', 'akt_fd_create_menu');
    function akt_fd_create_menu () {
    add_menu_page( 'My Options Page', 'My Option', 'administrator', 'akt_fd_menu', 'akt_fd_options');
    }
    function akt_fd_options () {
    echo 'bacon';
    }

    This works as expected. Now I want to add the css/js/whatever to the <head>, but only when "My Option" menu is clicked, not for other things like Settings, Dashboard, etc. I tried:

    function akt_fd_options () {
    add_action( 'admin_head', 'akt_fd_addtohead' );
    echo 'bacon';
    }
    function akt_fd_addtohead() {
    echo '<link rel="stylesheet" type="text/css" href="view.css" media="all">';
    }

    but it didn't work. I imagine it's too late at this stage to add to the head.

  2. AK Ted
    Member
    Posted 1 year ago #

    Nevermind. I found the "correct" way to add styles to the head is to register them, then enqueue when needed:
    wp_register_style and wp_enqueue_style

    Here's some sample code that creates the menu and injects the stylesheet to the <head> only when needed:

    add_action( 'admin_init', 'akt_fd_init' );
    function akt_fd_init() {
        wp_register_style( 'akt_fd_style', plugins_url('/css/style.css', __FILE__) );
    }
    
    add_action('admin_menu', 'akt_fd_create_menu');
    function akt_fd_create_menu () {
        $akt_fd_menu = add_menu_page( 'My Options Page', 'My Option', 'administrator', 'akt_fd_menu', 'akt_fd_options');
        add_action( 'admin_print_styles-' . $akt_fd_menu, 'akt_fd_add_styles' );
    }
    
    function akt_fd_add_styles() {
        wp_enqueue_style( 'akt_fd_style' );
    }
    
    function akt_fd_options () {
        echo '<div class="akt_bacon">bacon</div>';
    }

Topic Closed

This topic has been closed to new replies.

About this Topic