问题
I've made a Wordpress plugin, and I'm trying to add javascript to the admin head. I've tried but couldn't managed to do it, could anyone help? Bellow is what I was going with:
function __construct() {
add_action('wp_head', 'wpb_hook_javascript');
}
function wpb_hook_javascript() {
?>
<script>
// javscript code
</script>
<?php
}
回答1:
You need OOP structured solution which is following.
class testing {
public function __construct() {
add_action( 'admin_head', array($this, 'admin_script'), 10 );
}
public function admin_script() {
if ( is_admin() ) {
echo '<script type="text/javascript">
</script>';
};
}
}
// class object/instance
new testing();
回答2:
You should use the admin_head
action hook.
<?php
add_action( 'admin_head', 'admin_script' );
function admin_script() {
if ( is_admin() && strpos( $_SERVER[ 'REQUEST_URI' ], 'edit-tags.php?taxonomy=category' ) ) {
echo '<script type="text/javascript">
</script>';
};
}; ?>
Using $_SERVER[ 'REQUEST_URI' ]
we can also specified pages on the admin side to improved our conditional scripts loading. For example, here, we are only running our script on the post categories management page from the admin console.
Like pointed out in the comment, is_admin()
is just here as a redundancy.
Learn more
admin_head
@ https://developer.wordpress.org/reference/hooks/admin_head/
回答3:
Note: this would only apply on the frontend. See @amarinediary's answer for the correct Admin implementation.
Your code to add the hook is currently inside of a __construct()
function, which would only be triggered automatically if the plugin is a PHP Class. Try taking the add_action
hook out of that and putting it at the same level as the other function.
add_action('wp_head', 'wpb_hook_javascript');
function wpb_hook_javascript() {
?>
<script>
// javscript code
</script>
<?php
回答4:
this works!
add_action( 'wp_head', array( $this, 'function_name' ));
来源:https://stackoverflow.com/questions/65526056/adding-script-via-plugins-in-the-admin-head