Skip to content

Commit

Permalink
Added: server-side compatibility fix for CF7
Browse files Browse the repository at this point in the history
  • Loading branch information
Dan0sz committed Jan 22, 2025
1 parent 2e1a083 commit d60726b
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/Integrations/FormSubmit.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

namespace Plausible\Analytics\WP\Integrations;

use Plausible\Analytics\WP\Proxy;

class FormSubmit {
/**
* Build class.
Expand All @@ -25,13 +27,21 @@ private function init() {
* Adds required JS and classes.
*/
add_action( 'wp_enqueue_scripts', [ $this, 'add_js' ], 1 );
/**
* Contact Form 7 doesn't respect JS checkValidity() function.
*/
add_filter( 'wpcf7_validate', [ $this, 'wpcf7_validate' ], 10, 2 );
}

/**
* Enqueues the required JavaScript for form submissions integration.
* @return void
*/
public function add_js() {
if ( defined( 'WPCF7_VERSION' ) ) {
return;
}

wp_register_script(
'plausible-form-submit-integration',
PLAUSIBLE_ANALYTICS_PLUGIN_URL . 'assets/dist/js/plausible-form-submit-integration.js',
Expand All @@ -47,4 +57,31 @@ public function add_js() {

wp_enqueue_script( 'plausible-form-submit-integration' );
}

/**
* Tracks the form submission if form is valid.
*
* @param \WPCF7_Validation $result Form submission result object containing validation results.
* @param array $tags Array of tags associated with the form fields.
*
* @return \WPCF7_Validation
*/
public function wpcf7_validate( $result, $tags ) {
$invalid_fields = $result->get_invalid_fields();

if ( empty( $invalid_fields ) ) {
$post = get_post( $_POST[ '_wpcf7_container_post' ] );
$uri = '/' . $post->post_name . '/';

$proxy = new Proxy( false );
$proxy->do_request(
__( 'Form Completions', 'plausible-analytics' ),
null,
null,
[ 'form' => $uri ]
);
}

return $result;
}
}

0 comments on commit d60726b

Please sign in to comment.