简体   繁体   English

每次创建新帖子时,如何取消选中自定义元框中的复选框值?

[英]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. 我正在创建一个WordPress插件,并且有一个包含一些复选框的自定义元框。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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