Search code examples
csswordpressstylesheet

Adding a stylesheet to my option page


I have this code below my file name isYPE-Options.php file root is panel/YPE-Options.php and my stylesheet root is panel/css/bootstrap.min.css. I want add/load or register this stylesheet within this below code

How can I do this?

<?php

class YPE_Admin_Panel {

    public function __construct() {
        add_action('admin_menu', array($this, 'YPE_add_menu_page'));
    }

    public function YPE_add_menu_page() {
        //add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
        add_menu_page(
            'YALLANPE', 
            'YALLANPE', 
            'manage_options',
            'YPE_menu_page_options', 
            array($this,'YPE_display_admin_panel_options'), 
            '' 
        );
    }

    public function YPE_display_admin_panel_options() {
    ?>
        <h2>Yallanpe Blog Theme Settings</h2>
    <?php
    }

}

$YPE_Admin_Panel = new YPE_Admin_Panel();

Solution

  • The function add_menu_page() returns the hook name used to track our custom page. It can be used like:

    $hook = add_menu_page( $arguments );
    add_action( "admin_print_scripts-$hook", 'my_enqueue_callback' );
    

    But admin_print_scripts() is recommended only to print inline scripts. To enqueue, there is admin_enqueue_scripts() which receives the $hook as parameter.

    Full example:

    class YPE_Admin_Panel 
    {
        public $plugin_url;
        public $plugin_path;
        private $hook;
    
        public function __construct() 
        {
            $this->plugin_url    = plugins_url( '/', __FILE__ );
            $this->plugin_path   = plugin_dir_path( __FILE__ );
            add_action('admin_menu', array($this, 'menu_page'));
        }
    
        public function menu_page() 
        {
            $this->hook = add_menu_page(
                'YALLANPE', 
                'YALLANPE', 
                'manage_options',
                'YPE_menu_page_options', 
                array( $this,'display_panel' ), 
                '' 
            );
            add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
        }
    
        public function display_panel() 
        {
            ?><h2>Yallanpe Blog Theme Settings</h2><?php
        }
    
        public function enqueue( $hook )
        {
            // Not our page, bail out
            if( $hook !== $this->hook )
                return;
    
            wp_enqueue_style( 'my-style', $this->plugin_url . 'css/custom.css' );
        }
    }
    
    $YPE_Admin_Panel = new YPE_Admin_Panel();