如何验证自定义帖子类型中的自定义字段?

时间:2012-08-28 作者:Force Flow

我编写了一个插件,可以创建带有自定义字段的自定义帖子类型。为了防止用户输入错误信息,如何验证数据?

我假设save\\u post hook函数将处理字段验证,但我似乎找不到一种直接向用户显示错误的方法。

是否有内置的wordpress功能?完成自定义字段验证的一般技术是什么?

5 个回复
最合适的回答,由SO网友:Ian Dunn 整理而成

你在正确的轨道上。我在save_post 回调,然后使用admin notices 当字段验证失败时,向用户显示错误。它们显示在页面顶部的突出显示框中,就像WordPress本身生成的任何错误/消息一样。

下面是创建管理通知的简单示例:

function my_admin_notice()
{
    ?>

    <div class="updated">
       <p>Aenean eros ante, porta commodo lacinia.</p>
    </div>

    <?php
}
add_action( \'admin_notices\', \'my_admin_notice\' );
不过,这并不太实际。在这种情况下,您实际上只需要一个可以传递消息的函数。比如,

if( $pizza != \'warm\' )
    $notices->enqueue( \'Pizza is not warm\', \'error\' );
所以,你可以这样写enqueue() 您可以自己使用函数(以及打印通知的函数),也可以包括一个库,如IDAdminNotices.

以下是a plugin I wrote. 这使用内置于类本身的通知排队/打印函数,而不包括外部库。

public function saveCustomFields( $postID )
{
    // ...

    if( filter_var( $_POST[ self::PREFIX . \'zIndex\'], FILTER_VALIDATE_INT ) === FALSE )
    {
        update_post_meta( $post->ID, self::PREFIX . \'zIndex\', 0 );
        $this->enqueueMessage( \'The stacking order has to be an integer.\', \'error\' );
    }   
    else
        update_post_meta( $post->ID, self::PREFIX . \'zIndex\', $_POST[ self::PREFIX . \'zIndex\'] );

    // ...
}
add_action( \'save_post\',    array( $this, \'saveCustomFields\' );

SO网友:Kevin Phillips

我编写了一个小插件,它不仅可以验证自定义帖子类型上的输入字段,还可以删除默认的管理通知,而不使用Javascript。

下面是一些代码

/验证筛选器

$title = $album->post_title;
if ( ! $title ) {
    $errors[\'title\'] = "The title is required";
}

// if we have errors lets setup some messages
if (! empty($errors)) {

    // we must remove this action or it will loop for ever
    remove_action(\'save_post\', \'album_save_post\');

    // save the errors as option
    update_option(\'album_errors\', $errors);

    // Change post from published to draft
    $album->post_status = \'draft\';

    // update the post
    wp_update_post( $album );

    // we must add back this action
    add_action(\'save_post\', \'album_save_post\');

    // admin_notice is create by a $_GET[\'message\'] with a number that wordpress uses to
    // display the admin message so we will add a filter for replacing default admin message with a redirect
    add_filter( \'redirect_post_location\', \'album_post_redirect_filter\' );
}
您可以查看完整的教程here

SO网友:Lucas Bustamante

何时save_post 运行时,它已将帖子保存在数据库中

如果您使用的是ACF,它具有内置验证。

然而,如果您需要验证ACF之外的内容,例如post\\u title,那么事情会变得更加复杂。

查看WordPress核心代码,尤其是wp-includes/post.php\'supdate_post() 函数,在将请求保存到数据库之前,没有内置的方法来拦截请求。

然而,我们可以钩住pre_post_update 和使用header()get_post_edit_link() 阻止保存帖子。

<?php

/**
*   Performs custom validation on custom post type "Site"
*/
function custom_post_site_save($post_id, $post_data) {
    # If this is just a revision, don\'t do anything.
    if (wp_is_post_revision($post_id))
        return;

    if ($post_data[\'post_type\'] == \'site\') {
        # In this example, we will raise an error for post titles with less than 5 characters
        if (strlen($post_data[\'post_title\']) < 5) {
            # Add a notification
            update_option(\'my_notifications\', json_encode(array(\'error\', \'Post title can\\\'t be less than 5 characters.\')));
            # And redirect
            header(\'Location: \'.get_edit_post_link($post_id, \'redirect\'));
            exit;
        }
    }
}
add_action( \'pre_post_update\', \'custom_post_site_save\', 10, 2);

/**
*   Shows custom notifications on wordpress admin panel
*/
function my_notification() {
    $notifications = get_option(\'my_notifications\');

    if (!empty($notifications)) {
        $notifications = json_decode($notifications);
        #notifications[0] = (string) Type of notification: error, updated or update-nag
        #notifications[1] = (string) Message
        #notifications[2] = (boolean) is_dismissible?
        switch ($notifications[0]) {
            case \'error\': # red
            case \'updated\': # green
            case \'update-nag\': # ?
                $class = $notifications[0];
                break;
            default:
                # Defaults to error just in case
                $class = \'error\';
                break;
        }

        $is_dismissable = \'\';
        if (isset($notifications[2]) && $notifications[2] == true)
            $is_dismissable = \'is_dismissable\';

        echo \'<div class="\'.$class.\' notice \'.$is_dismissable.\'">\';
           echo \'<p>\'.$notifications[1].\'</p>\';
        echo \'</div>\';

        # Let\'s reset the notification
        update_option(\'my_notifications\', false);
    }
}
add_action( \'admin_notices\', \'my_notification\' );

SO网友:Alan Tygel

我只想补充一下@Lucas Bustamante的优秀答案,自定义字段的值可以通过$_POST 全球的

因此,如果验证引用自定义字段,@Lucas Bustamante answer也是有效的。例如:

<?php

/**
*   Performs custom validation on custom post type "Site"
*/
function custom_post_site_save($post_id, $post_data) {
    # If this is just a revision, don\'t do anything.
    if (wp_is_post_revision($post_id))
        return;

    if ($post_data[\'post_type\'] == \'site\') {
        # In this example, we will raise an error for post titles with less than 5 characters
        if (strlen($_POST[\'zip_code\']) < 5) {
            # Add a notification
            update_option(\'my_notifications\', json_encode(array(\'error\', \'Zip code can\\\'t be less than 5 characters.\')));
            # And redirect
            header(\'Location: \'.get_edit_post_link($post_id, \'redirect\'));
            exit;
        }
    }
}
add_action( \'pre_post_update\', \'custom_post_site_save\', 10, 2);

/**
*   Shows custom notifications on wordpress admin panel
*/
function my_notification() {
    $notifications = get_option(\'my_notifications\');

    if (!empty($notifications)) {
        $notifications = json_decode($notifications);
        #notifications[0] = (string) Type of notification: error, updated or update-nag
        #notifications[1] = (string) Message
        #notifications[2] = (boolean) is_dismissible?
        switch ($notifications[0]) {
            case \'error\': # red
            case \'updated\': # green
            case \'update-nag\': # ?
                $class = $notifications[0];
                break;
            default:
                # Defaults to error just in case
                $class = \'error\';
                break;
        }

        $is_dismissable = \'\';
        if (isset($notifications[2]) && $notifications[2] == true)
            $is_dismissable = \'is_dismissable\';

        echo \'<div class="\'.$class.\' notice \'.$is_dismissable.\'">\';
           echo \'<p>\'.$notifications[1].\'</p>\';
        echo \'</div>\';

        # Let\'s reset the notification
        update_option(\'my_notifications\', false);
    }
}
add_action( \'admin_notices\', \'my_notification\' );
``

SO网友:xXxlazharxXx

您可以使用;wp\\U insert\\U post\\U数据“;在将数据插入数据库之前过滤到修改器或检查数据

add_filter( \'wp_insert_post_data\', \'validate_posttypes\' );
function wpb_custom_excerpt($data) {
    str_starts_with($data[\'post_title\'],\'wp\')?$data[\'post_title\']=\'wp\'.$data[\'post_title\']:null;
    return $data;
}

结束

相关推荐

Comment form validation

如何设置注释字段的验证规则?我更改了评论者姓名/电子邮件/主页onmouseover和onblur的值(我使用它而不是标签-因此如果字段为空,它会显示“您的电子邮件”、“您的主页”等)。问题是,在提交时,它会在主页字段中提交此文本(因为它没有验证,而不像电子邮件字段,如果您输入了除[email protected]).如何验证主页字段?