How can I load script and style in specific page in the back-end?

I am new in WordPress so I am building my first theme with theme options I am facing the problem in my theme options pages that I have made in admin. I have two different styles for my theme options in admin area when I enqueue scripts for admin the problem are as follows:

  1. When I enqueue the scripts the script loaded on all the admin pages I just want it to load it on my theme options page

  2. As I mentioned above that I have two different styles according to two different pages of theme options. How can I load the style accordingly?

2 Answers
2

So simple I will explain it step by step:

  1. First, use the $hook variable that is WordPress default like this:

    function the_themescripts($hook) {
        echo $hook;
    }
    add_action( 'admin_enqueue_scripts', 'dr_theme_options_style_scripts' );
    
  2. Now go to custom page in your admin WP Dashboard and at the top you will see something like
    toplevel_page_your_theme_page_slug if it does not visible to you try to inspect element and see after tag copy that and use like this.

  3. Use of $hook variable. Use it inside the if else loop

    function the_themescripts($hook) {
      echo $hook;
    
      if ($hook == 'toplevel_page_your_page_slug') :
          // enqueue your script/styles here for your first page    
      endif;
    
      if ($hook == 'your second page slug' ) :
          // enqueue your script/styles here for your first page
      endif
    }
    add_action( 'admin_enqueue_scripts', 'the_themescripts' );
    

Hope this explanation helps:)

Leave a Comment