How to add custom JavaScript in functions?

The question:

I want to write some JavaScript and want to assign that to a custom capability, I explored a lot but unfortunately none of them worked, any help will be appriciated.

My codes are as below:

add_action('init', function() {
    if (current_user_can('disable_image'))
    {
        //add javascript here
    }
});

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

function admin_footer_hook(){
        ?>
    <script type="text/javascript">
        
    </script>
<?php
}
add_action( 'admin_footer-post.php', 'admin_footer_hook' );

Method 2

Javascript is a client-side technology – in other words, it only runs on the rendered browser page. It seems to me like you’re looking for a server-side solution – ie, one that runs when the page is being built before it is delivered to the browser. So, you might want to rethink your approach.

However, it is possible to use javascript to make text fields, etc, uneditable, but how successful that would be depends on any existing JS which may also be affecting those fields. Either way, you would need to output your JS code to the page, and to do that you would need to use the right WordPress enqueue action, depending on your context.

So, if your form is on the user side of your site, you would enqueue your script using the wp_enqueue_scripts hook:

function my_enqueue_script() {
    if ( current_user_can('disable_image') )
        wp_enqueue_script( 'my_js', 'my-script.js', false );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_script' );

If your form is on the admin side, you would use the admin_enqueue_scripts hook:

function my_enqueue_admin_script( $hook ) {
    if ( 'edit.php' == $hook && current_user_can('disable_image') )
        wp_enqueue_script( 'my_admin_js', 'my-admin-script.js', array(), '1.0' );
}
add_action( 'admin_enqueue_scripts', 'my_enqueue_admin_script' );

(you would need to determine the exact admin page to apply this to – ‘edit.php’ is just an example)

You can find more info about both of these hooks from their respective Codex pages:
wp_enqueue_scripts: https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/
admin_enqueue_scripts: https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/

Hope that steers you in the right direction.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment