简体   繁体   中英

How to uncheck checkbox values in custom meta-box each time a new post is created?

I am creating a WordPress plugin and I have a custom meta-box which contains some checkboxes. Now I wanted to save state of these checkboxes even after page refresh, hence I'm doing this:

<script type="text/javascript">
(function() {
    var boxes = document.querySelectorAll("input[name='my_meta_box_check[]']");
    for (var i = 0; i < boxes.length; i++) {
        var box = boxes[i];
        if (box.hasAttribute("value")) {
            setupBox(box);
        }
    }

    function setupBox(box) {
        var storageId = box.getAttribute("value");
        var oldVal    = localStorage.getItem(storageId);
        box.checked = oldVal === "true" ? true : false;

        box.addEventListener("change", function() {
            localStorage.setItem(storageId, this.checked);
        }); 
    }
})();
</script>

And it works. But what happens is, whenever a new post is created, the checkboxes are checked with old values from last post. How do I refresh or uncheck all checkboxes when the post is created for the first time? I also tried deleting post meta from database if the post status is not yet published, like this:

if(get_post_status($post->ID)==='publish'){
    echo "<b>"."Post is published!"."</b></br>";
}
else
{
    global $wpdb;   
    global $post;
    echo "<b>"."Post is not published!"."</b></br>";    
    $wpdb->query("DELETE from wp_postmeta where post_id LIKE '$post->ID' AND meta_key='my_meta_box_check'");  

}

It executes the query, but the checkboxes are checked with values from the previous post.

You will need to clear your local storage after you submit the post.

If you want to remove/clean all the values from local storage than use

localStorage.clear();

And if you want to remove the specific item from local storage than use the following code

localStorage.removeItem(key);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM