Please find below a potential solution. It checks the status of the $id
for being a \WP_Error
(indicating the creation of the post failed). If it’s not a error, it’ll produce a simple message to give output the $id
.
However, it should be noted that the code you’ve provided has an error and will likely produce a fatal error, because $school
is undefined and you’re accessing it like an Object
. My code is based on your code and doesn’t correct for this. So you’ll need to apply this solution to your particular implementation and correct this.
Also, I’ve added $abort = true;
in the case of error, so the form submission will be aborted. You can keep that or remove it depending on your requirements.
add_action( 'wpcf7_before_send_mail', function ( $contact_form, &$abort, $submission ) {
if ( $contact_form->title == "Pledge" ) {
$name = $submission->get_posted_data( "pledge-name" );
$schoolid = $submission->get_posted_data( "yes" );
$id = wp_insert_post( [
"post_type" => "pledge",
"post_title" => "$school->name | $name",
"post_status" => "draft",
] );
if ( is_wp_error( $id ) ) {
$submission->set_response( 'There was an error creating the new post.' );
$abort = true;
}
else {
$submission->set_response( sprintf( 'A new post has been created with the ID: %s.', $id ) );
}
}
}, 10, 3 );
return !$abort;
}