0

I created a custom button on the "users" admin page. I have a script (loaded correctly) which should register the button click, but it doesn't.

I followed an example where they hooked the "admin_footer" tag. Inside the function, I the button is created with jquery. I placed this code in functions.php:

add_action('admin_footer', 'users_csv_button');

function users_csv_button() {
    $screen = get_current_screen();
    if ( $screen->id != "users" )   // Only add to users.php page
        return;
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {

            $("form .tablenav .alignleft").eq(1).after("<div class='alignleft actions valign_c' style='height:30px;'>" +
                "<input type='button' class='button' id='createcsv' value='CSV'></div>");

        });
    </script>

I added the script to the users.php page with "admin_enqueue_scripts" in functions.php:

function enqueue_js($page){
    if ($page != 'users.php'){
        return;
    }
    wp_enqueue_script( 'form', get_template_directory_uri() . '/js/form.js', array('jquery'), '1.0.0');
}
add_action('admin_enqueue_scripts', 'enqueue_js');

And the "form.js" script file looks like this:

jQuery(document).ready(function($){
    alert('form!'); //this happens


     $('#createcsv').click(function(){
            alert('createcsv button has been pressed'); //this doesn't happen
});

When the alert which says "form!" pops up, all of the page has loaded except the button, which loads after I press ok on the alert. I suspect I need to change the timing, but how?

  • Why not put both parts in form.js? Otherwise, see the section titled Delegated events for the on event handler. – Milo Nov 12 '15 at 18:31
  • Yes, I did it and deleted the "users_csv_button" function. I got it to work,and will comment on that tomorrow when I'm back at the computer. – Galivan Nov 12 '15 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.