[フレーム]
Last Updated: February 25, 2016
·
1.169K
· nicocrm

Enqueue scripts / styles on a Wordpress option page

My basic class for creating an option page:

class WPHooks
{
 const OPTION_PAGE_SLUG = 'rti_booker_sites';

 public function registerHooks()
 {
 add_action('admin_menu', array(&$this, 'adminMenu'));
 }

 public function adminMenu()
 {
 if (current_user_can('manage_options')) {
 add_options_page('Booker Site Manager', 'Booker Sites', 'manage_options',
 self::OPTION_PAGE_SLUG, array(&$this, 'renderOptionsPage'));
 }
 }

 public function renderOptionsPage()
 {
 require "OptionPage.php";
 }

}

If scripts are needed on the page and it just uses wp_enqueue_scripts to add it then it will put it in the page footer - this is not so bad for scripts but very undesirable for stylesheets.

Instead the proper way to enqueue scripts is to make use of the admin_enqueue_scripts action. But to ensure scripts are only included for our particular page and not polluting other pages in the admin, use this:

private $optionPageHookSuffix;

public function adminMenu() 
{
 $this->optionPageHookSuffix = add_options_page('Booker Site Manager', 'Booker Sites', 'manage_options',
 self::OPTION_PAGE_SLUG, array(&$this, 'renderOptionsPage'));
 add_action('admin_enqueue_scripts', array(&$this, 'enqueueScripts'));
}

public function enqueueScripts($hookSuffix)
{
 if ($hookSuffix == $this->optionPageHookSuffix) {
 wp_enqueue_script('bootstrap-js', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js', ['jquery']);
 wp_enqueue_script('jquery-validation', \Roots\Sage\Assets\asset_path('scripts/jquery-validate.js'), ['jquery']);
 wp_enqueue_style('bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css');
 wp_enqueue_style('admin-css', \Roots\Sage\Assets\asset_path('styles/admin-style.css'));
 }
}

AltStyle によって変換されたページ (->オリジナル) /