Commit 6efa675821 for woocommerce

commit 6efa675821faf1fa4901e1675b071a226137747a
Author: Thomas Roberts <5656702+opr@users.noreply.github.com>
Date:   Tue Dec 9 14:32:17 2025 +0000

    Prevent `wc_add_notice` trying to add notices if session is not initialized (#62310)

    * Prevent wc_add_notice trying to add if session is not initialized

    * Add changelog

    * Add tests for adding notices with no session

    * Add doing_it_wrong message

    * Update test for new doing it wrong notice

    * Use correct version in doing_it_wrong

diff --git a/plugins/woocommerce/changelog/fix-check-session-before-accessing b/plugins/woocommerce/changelog/fix-check-session-before-accessing
new file mode 100644
index 0000000000..f58e3af4da
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-check-session-before-accessing
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Prevent errors when plugins incorrectly call wc_add_notice before session is initialized
diff --git a/plugins/woocommerce/includes/wc-notice-functions.php b/plugins/woocommerce/includes/wc-notice-functions.php
index 3d7c4cf7b4..b1a715a8d5 100644
--- a/plugins/woocommerce/includes/wc-notice-functions.php
+++ b/plugins/woocommerce/includes/wc-notice-functions.php
@@ -79,6 +79,13 @@ function wc_add_notice( $message, $notice_type = 'success', $data = array() ) {
 		return;
 	}

+	// If this is called before the session is initialized, for example if a plugin includes this file incorrectly on
+	// the admin, skip doing anything to prevent errors.
+	if ( ! WC()->session ) {
+		wc_doing_it_wrong( __FUNCTION__, __( 'This function should not be called before the WooCommerce session is initialized, or places where there is no session, e.g. WordPress admin.', 'woocommerce' ), '10.5' );
+		return;
+	}
+
 	$notices = WC()->session->get( 'wc_notices', array() );

 	// Backward compatibility.
diff --git a/plugins/woocommerce/tests/legacy/unit-tests/util/notice-functions.php b/plugins/woocommerce/tests/legacy/unit-tests/util/notice-functions.php
index 4e0a42ba3d..6c78d1a389 100644
--- a/plugins/woocommerce/tests/legacy/unit-tests/util/notice-functions.php
+++ b/plugins/woocommerce/tests/legacy/unit-tests/util/notice-functions.php
@@ -250,4 +250,24 @@ class WC_Tests_Notice_Functions extends WC_Unit_Test_Case {

 		WC()->session = $original_session;
 	}
+
+	/**
+	 * Test wc_add_notice() with no session.
+	 */
+	public function test_wc_add_notice_no_session() {
+		$this->setExpectedIncorrectUsage( 'wc_add_notice' );
+
+		$original_session = WC()->session;
+
+		WC()->session = null;
+
+		// Should not throw an error when session is null, but should trigger doing_it_wrong.
+		wc_add_notice( 'Test Notice' );
+
+		WC()->session = $original_session;
+
+		// Notice should not have been added since there was no session.
+		$notices = wc_get_notices();
+		$this->assertEmpty( $notices );
+	}
 }