diff --git a/src/wp-includes/comment-template.php b/src/wp-includes/comment-template.php
index 6a27a67d92..63614663de 100644
--- a/src/wp-includes/comment-template.php
+++ b/src/wp-includes/comment-template.php
@@ -2324,13 +2324,14 @@ function wp_list_comments( $args = array(), $comments = null ) {
function comment_form( $args = array(), $post = null ) {
$post = get_post( $post );
- $post_id = $post ? $post->ID : get_the_ID();
-
- // Exit the function when comments for the post are closed.
- if ( ! comments_open( $post_id ) ) {
+ // Exit the function if the post is invalid or comments are closed.
+ if ( ! $post || ! comments_open( $post ) ) {
/**
* Fires after the comment form if comments are closed.
*
+ * For backward compatibility, this action also fires if comment_form()
+ * is called with an invalid post object or ID.
+ *
* @since 3.0.0
*/
do_action( 'comment_form_comments_closed' );
@@ -2338,6 +2339,7 @@ function comment_form( $args = array(), $post = null ) {
return;
}
+ $post_id = $post->ID;
$commenter = wp_get_current_commenter();
$user = wp_get_current_user();
$user_identity = $user->exists() ? $user->display_name : '';
diff --git a/tests/phpunit/tests/comment/commentForm.php b/tests/phpunit/tests/comment/commentForm.php
index e9e6d99e73..05a9269ffb 100644
--- a/tests/phpunit/tests/comment/commentForm.php
+++ b/tests/phpunit/tests/comment/commentForm.php
@@ -153,4 +153,44 @@ class Tests_Comment_CommentForm extends WP_UnitTestCase {
$expected = '';
$this->assertStringNotContainsString( $expected, $form );
}
+
+ /**
+ * @ticket 56243
+ */
+ public function test_comment_form_should_not_display_for_global_post_when_called_with_invalid_id() {
+ // Go to permalink to ensure global post ID is set.
+ $this->go_to( get_permalink( self::$post_id ) );
+
+ $impossibly_high_post_id = PHP_INT_MAX;
+
+ $form = get_echo( 'comment_form', array( array(), $impossibly_high_post_id ) );
+ $this->assertEmpty( $form );
+ }
+
+ /**
+ * @ticket 56243
+ */
+ public function test_comment_form_should_display_for_global_post_with_falsey_post_id() {
+ $post_id = self::$post_id;
+ $this->go_to( get_permalink( $post_id ) );
+
+ $form = get_echo( 'comment_form', array( array(), false ) );
+ $this->assertNotEmpty( $form );
+
+ $post_hidden_field = "";
+ $this->assertStringContainsString( $post_hidden_field, $form );
+ }
+
+ /**
+ * @ticket 56243
+ */
+ public function test_comment_form_should_display_for_specified_post_when_passed_a_valid_post_id() {
+ $post_id = self::$post_id;
+
+ $form = get_echo( 'comment_form', array( array(), $post_id ) );
+ $this->assertNotEmpty( $form );
+
+ $post_hidden_field = "";
+ $this->assertStringContainsString( $post_hidden_field, $form );
+ }
}