|
1 | 1 | <?php |
2 | 2 | namespace VendorName\PluginName; |
| 3 | +use WordPress_ToolKit\ScriptObject; |
3 | 4 |
|
4 | 5 | class EnqueueScripts extends Plugin { |
5 | 6 |
|
6 | 7 | function __construct() { |
7 | 8 |
|
8 | | - // Enqueue frontend/backend scripts and global JavaScript variables |
9 | | - add_action( 'wp_head', array( $this, 'inject_javascript_settings' ) ); |
10 | | - add_action( 'admin_head', array( $this, 'inject_javascript_settings' ) ); |
| 9 | + // Enqueue frontend/backend scripts |
11 | 10 | add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_scripts') ); |
12 | 11 | add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts') ); |
13 | 12 |
|
| 13 | + // Inject plugin settings into page head |
| 14 | + $this->inject_javascript_settings(); |
| 15 | + |
14 | 16 | // Example - Load Font Awesome from CDN, if enabled in Settings Page |
15 | 17 | $enqueue_font_awesome = $this->get_plugin_option( 'enqueue_font_awesome' ); |
16 | 18 | if( $enqueue_font_awesome ) { |
@@ -80,19 +82,25 @@ public function enqueue_font_awesome() { |
80 | 82 | } |
81 | 83 |
|
82 | 84 | /** |
83 | | - * Add global JavaScript settings variables. You can add any variables/settings |
84 | | - * that you want to make available to your JavaScripts |
| 85 | + * Inject JavaScript settings into header. You can add any variables/settings |
| 86 | + * that you want to make available to your JavaScripts. |
85 | 87 | * @since 0.3.0 |
86 | 88 | */ |
87 | | - public function inject_javascript_settings() { |
| 89 | + private function inject_javascript_settings() { |
| 90 | + |
| 91 | + $args = array( |
| 92 | + 'variable_name' => $this->prefix( 'plugin_settings', '_' ), |
| 93 | + 'target' => ['wp', 'admin'] |
| 94 | + ); |
88 | 95 |
|
89 | | - $javascript_variables = array( |
| 96 | + $values = array( |
90 | 97 | 'admin_bar_add_clear_cache' => $this->get_plugin_option( 'admin_bar_add_clear_cache' ), |
91 | 98 | 'admin_bar_add_clear_cache_success' => __( 'WordPress cache has been cleared.', self::$textdomain ), |
92 | | - 'show_clear_cache_link' => current_user_can( 'manage_options' ) |
| 99 | + 'show_clear_cache_link' => current_user_can( 'manage_options' ), |
93 | 100 | ); |
94 | 101 |
|
95 | | - echo "<script>var _wpbp_plugin_settings = JSON.parse('" . json_encode( $javascript_variables ) . "');</script>"; |
| 102 | + $js = new \WordPress_ToolKit\ScriptObject( $values ); |
| 103 | + $js->injectJS( $args ); |
96 | 104 |
|
97 | 105 | } |
98 | 106 |
|
|
0 commit comments