php - 如何向 Wordpress 发布按钮添加确认对话框?

标签 php wordpress

<分区>

我正在开发一个 wordpress 插件,它创建一个带有一些特殊字段的自定义帖子类型“知识库文章”。如果用户在提交之前缺少字段,我希望发布按钮能够警告用户。我该怎么做呢?是否有适当的 Hook 来插入此行为?

最佳答案

您可以在 wp-admin/js/common.js 中使用基本的客户端表单验证脚本,它默认包含在所有管理页面中。

首先,通过在帖子编辑屏幕上运行的插件添加一个操作:

add_action('admin_print_scripts', 'my_validation_script');
function my_validation_script() {
    global $post_type;
    if(isset($post_type) && $post_type == 'knowledgebase_article') {
        wp_enqueue_script('my-validation-script', network_site_url() . '/wp-content/plugins/your-plugin-folder/my-validation-script.js', array('jquery', 'common'));
    }
}

接下来,编写小的 javascript 表单处理程序来实际处理表单提交:

jQuery(document).ready(function(){

    //'my_required_field' is the class name of the DIV or TD tag *containing* the required form field
    jQuery('.my_required_field').addClass('form-required'); 

    //'post' is the ID of the main form on the new post screen
    jQuery('#post').submit(function(){ 
            //the validateForm function lives in wp-admin/js/common.js
            if ( !validateForm( jQuery(this)) ) { 
                    alert('Please enter a value'); 
                    return false; //stop submitting the form
            } else {
                    //alert('all required fields have some input');
            }
    });

});

您可以通过访问标签编辑页面查看此验证器的行为,然后创建一个没有名称的新标签。该字段的容器变为红色,提醒您注意问题。

我在我这边测试了这个并且它有效。希望对您有所帮助。

关于php - 如何向 Wordpress 发布按钮添加确认对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6711823/

相关文章:

javascript - 隐藏父级的 jQuery 脚本不起作用 - Wordpress

php - 根据数据库中所选值的下拉菜单

php - mysql在一个字段中存储多个条目

javascript - 将 POST 更改为 GET。现在 Ajax 返回多个帖子

php - Woocommerce:帮助替换 html 输出

wordpress csv导出在输出中包含html

php - 多于2 and,3 or条件的sql查询(mysql)

javascript - 如何在选择文件后立即上传图像,而不是强制用户单击单独的 "Upload"按钮?

php - Laravel 5 资源链接

php - 当它应该是内联时,标题上方的 Wordpress 正文