2

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

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:)

2

To detect the current page in the admin panel, you can use a global variable named $pagenow. Take a look at this example:

function my_admin_enqueue() {
    global $pagenow;
    // Get the current page
    if (isset($_GET['page'])) {
        $current_page = $_GET['page'];
    } else {
        $current_page = '';
    }
    // Check both current page base and slug
    if( ( $pagenow == 'themes.php' ) && ( $current_page == 'my-theme-settings' ) ) {
        // Now enqueue your script and styles here
    }
}
add_action('admin_enqueue_scripts', 'my_admin_enqueue');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.