WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How can I add scripts/styles for specific plugin page in Admin? (6 posts)

  1. Travis Smith
    Member
    Posted 3 years ago #

    So I currently register my plugin settings page as such:

    //	this function adds the settings page to the Appearance tab
    add_action('admin_menu', 'add_wp_accordion_menu');
    function add_wp_accordion_menu() {
    	add_submenu_page('upload.php', 'WP Accordion Settings', 'WP Accordion', 'upload_files', 'wp-accordion', 'wp_accordion_admin_page');
    }

    When I use these actions, everything works fine:

    add_action( 'admin_print_scripts' , 'wp_accordion_jquery' );
    add_action( 'admin_print_scripts' , 'wp_accordion_scripts' );
    add_action( 'admin_print_styles' , 'wp_accordion_styles' );
    add_action( 'admin_head', 'wp_accordion_style' );
    add_action( 'admin_head', 'wp_accordion_args' );

    However, I'd rather only call the scripts/styles only when my plugin page is called, so I tried:

    add_action( 'admin_print_scripts-wp-accordion' , 'wp_accordion_jquery' );
    add_action( 'admin_print_scripts-wp-accordion' , 'wp_accordion_scripts' );
    add_action( 'admin_print_styles-wp-accordion' , 'wp_accordion_styles' );
    add_action( 'admin_head-wp-accordion', 'wp_accordion_style' );
    add_action( 'admin_head-wp-accordion', 'wp_accordion_args' );

    However, it is not working. So what am I doing wrong?

  2. What does the final URL look like when on the page?

  3. Travis Smith
    Member
    Posted 3 years ago #

  4. Do this:

    if (isset($_GET['page'] && $_GET['page'] == 'wp-accordion) {
        add_action( 'admin_print_scripts-wp-accordion' , 'wp_accordion_jquery' );
    }'
  5. Travis Smith
    Member
    Posted 3 years ago #

    Modified code (and function name changed for clarity):

    // Admin when you plugin page is called
    add_action( 'init' , 'wp_accordion_admin' );
    function wp_accordion_admin() {
    	if (isset($_GET['page']) && $_GET['page'] == 'wp-accordion') {
    		add_action( 'admin_print_scripts' , 'wp_accordion_scripts' );
    		add_action( 'admin_print_scripts' , 'wp_accordion_admin_script' );
    		add_action( 'admin_print_styles' , 'wp_accordion_styles' );
    		add_action( 'admin_head', 'wp_accordion_dyn_style' );
    		add_action( 'admin_head', 'wp_accordion_dyn_script' );
    	}
    }
  6. You don't need to place the print styles / scripts actions inside of another function.

    function enqueue_scripts() {
        // do your enqueues here
    }
    function echo_scripts_to_head() {
        // echo your scripts to be placed in the header here
    }
    function enqueue_styles() {
         // enqueue your styles here
    }
    
    if (isset($_GET['page']) && $_GET['page'] == 'wp-accordion') {
        // do all of your add_action() hooks here
    }

Topic Closed

This topic has been closed to new replies.

About this Topic