Question

In wordpress backend -> add new post area, how to do something Immediately after metabox -> checkbox is checked, for example when I checked a category:

this is the the checkbox before checked:

<input value="1" type="checkbox" name="post_category[]" id="in-category-1">

this is the the checkbox after checked:

<input value="1" type="checkbox" name="post_category[]" id="in-category-1">
::before
</input>

SO, how to Detect the checkbox is checked and do function Immediately after it checked?

Was it helpful?

Solution

You can achieve that using jQuery.

!(function($){
$(document).ready(function(){
    $('#categorychecklist').on('change', 'input[type=checkbox]', function(){
        if ($(this).is(':checked'))
            alert('Category' + $(this).closest('label').text() + ' added.');
        else
            alert('Category' + $(this).closest('label').text() + ' removed.');
    });
});
})(window.jQuery);

/wp-content/themes/themename/js/post-jquery.js

I have this to say which category is added or removed after they are being ticked or unticked (change event).

To attach this jQuery. I check if the current page is adding/editing post with get_current_screen() like so.

<?php
function add_script_to_post() {
    $current_screen = get_current_screen();
    if ( $current_screen->base == 'post' ) { // Check if is adding/editing post
        wp_enqueue_script('post-jquery', get_stylesheet_directory_uri() . '/js/post-jquery.js');
    }
}
add_action('current_screen', 'add_script_to_post');
?>

/wp-content/themes/themename/functions.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top