Why is_wp_error() is not returning false even there’s no defined error
Question
On the form submission I’m taking user comment for a custom purpose for my plugin. I’m checking whether the comment field is empty or not, and the comment field is filled with at least 30 characters. If both are ok, I want to insert the comment.
Here’s my code:
<?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>
But on submission of the form, if I var_dump( $error );
:
object(WP_Error)[398]
public 'errors' =>
array (size=0)
empty
public 'error_data' =>
array (size=0)
empty
it’s empty, but still the if( is_wp_error( $error ) ) { echo 1; }
is showing 1
. And that’s why the comment is not inserting.
What am I doing wrong?
0
2 years
2020-12-13T23:10:49-05:00
2020-12-13T23:10:49-05:00 0 Answers
13 views
0
Leave an answer