Почему wp error() не возвращает false, даже если нет определенной ошибки


При отправке формы я беру комментарий пользователя для специальной цели для моего плагина. Я проверяю, является ли поле комментария пустым или нет, и поле комментария заполнено не менее чем 30 символами. Если оба в порядке, я хочу вставить комментарий.

Вот мой код:

<?php
global $current_user, $post;

if( isset( $_POST['send'] ) && isset( $_POST['test_nonce'] ) && wp_verify_nonce( $_POST['test_nonce'], 'testify_nonce' ) ) {
    //global $error;
    $error = new WP_Error();

    $comment_content = $_POST['comment_content'];

    if( empty( $comment_content ) ) {
        $error->add( 'comment_empty', __("Comment field can't be empty.") );
    }
    if ( strlen( $comment_content ) < 30 ) {
        $error->add( 'comment_short', __("Your comment is too short. Write down at least 30 characters.") );
    }

    //test test test
    var_dump($error);
    if( is_wp_error( $error ) ) { echo 1; }
    //test test test

    if( is_wp_error( $error ) ) {
        echo '<div class="alert alert-danger" role="alert">';
            echo $error->get_error_message();
        echo '</div>';
    } else {
        $commentdata = array(
            'comment_post_ID'       => $post->ID,
            'comment_author'        => $current_user->display_name, 
            'comment_author_email'  => $current_user->user_email,
            'comment_author_url'    => $current_user->user_url,
            'comment_content'       => htmlentities( $comment_content ),
            'comment_type'          => '',
            'comment_parent'        => 0,
            'user_id'               => $current_user->ID,
            'comment_approved'      => '1' //approve by default
        );

        //Insert new comment and get the comment ID
        $comment_id = wp_insert_comment( $commentdata );

        if( ! is_wp_error( $comment_id ) ) {
            echo '<div class="alert alert-success" role="alert">';
                _e( 'Your comment is successfully submitted.', 'text-domain' );
            echo '</div>';
        } else {
            echo '<div class="alert alert-danger" role="alert">';
                echo $comment_id->get_error_message();
            echo '</div>';
        } //endif( ! is_wp_error( $comment_id ) )
    } //endif( is_wp_error( $error ) )        
} //endif( $_POST['send'] )
?>
<form method="post" enctype="multipart/form-data">
    <textarea name="comment_content" id="" class="form-control" rows="6"></textarea>
    <?php wp_nonce_field( 'testify_nonce', 'test_nonce' ); ?>
    <button type="submit" name="send" class="btn btn-primary"><?php _e( 'Submit', 'text-domain' ); ?></button>
</form>

Но при подаче формы, если я var_dump( $error );:

object(WP_Error)[398]
  public 'errors' => 
    array (size=0)
      empty
  public 'error_data' => 
    array (size=0)
      empty

Он пуст, но все равно if( is_wp_error( $error ) ) { echo 1; } показывает 1. И именно поэтому комментарий не вставляется.

Кто я такой поступаешь неправильно?

Author: Mayeenul Islam, 2015-05-15

1 answers

Функция is_wp_error проверяет, является ли данный var экземпляром класса WP_Error ( исходный код как WP 4.2.2):

function is_wp_error( $thing ) {
    return ( $thing instanceof WP_Error );
}

Как вы можете видеть, если данная переменная является экземпляром класса WP_Error, функция возвращает значение true, даже если объект пуст. Ваша переменная $error является экземпляром WP_Error, пустым, но экземпляром WP_Error, поэтому она возвращает значение true. Вы могли бы что-нибудь сделать:

if ( is_wp_error( $error ) && ! empty( $error->errors ) )

Или инициировать WP_Error только при определенных условиях (напишите здесь, не проверено):

$errors = array();

if ( empty( $comment_content ) ) {
    $errors['comment_empty'] = esc_html__("Comment field can't be empty.");
}
if ( strlen( $comment_content ) < 30 ) {
    $errors['comment_short'] = esc_html__("Your comment is too short. Write down at least 30 characters.");
}

if( ! empty( $errors ) ) {

    $wp_error = new WP_Error();
    foreach ( $errors as $code => $message ) {
        $wp_error->add( $code, $message );
    }

}

if ( is_wp_error( $wp_error ) ) {
}
 4
Author: cybmeta, 2020-12-14 04:32:14