Created
March 3, 2020 16:47
-
-
Save yeriepiscesa/9132c8a1ace9e00003fed1799f0fac59 to your computer and use it in GitHub Desktop.
Send Contact Form 7 to WhatsApp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SP_Contact_Form_WA { | |
protected $ids = array(); | |
protected $script_loaded = false; | |
protected $bodies = array(); | |
protected $numbers = array(); | |
public function __construct() { | |
add_shortcode( 'contact-form-7-wa', array( $this, 'render_contact_form' ) ); | |
add_action( 'wp_footer', array( $this, 'render_script_footer' ), 99 ); | |
} | |
public function render_contact_form( $atts ) { | |
wp_enqueue_script( 'underscore' ); | |
$shortcode = '[contact-form-7'; | |
if( isset( $atts['number'] ) && $atts['number'] != '' ) { | |
$this->numbers[$atts['id']] = $atts['number']; | |
unset( $atts['number'] ); | |
} | |
foreach( $atts as $key=>$val ) { | |
$shortcode .= ' ' . $key .'="' . $val . '"'; | |
} | |
$shortcode .= ']'; | |
$html = do_shortcode( $shortcode ); | |
array_push( $this->ids, intval($atts['id']) ); | |
$_mail = get_post_meta( $atts['id'], '_mail', true ); | |
if( $_mail && isset( $_mail['body'] ) ) { | |
$this->bodies[$atts['id']] = $_mail['body']; | |
} | |
return $html; | |
} | |
public function render_script_footer() { | |
if( !empty( $this->ids ) && !$this->script_loaded ) : ?> | |
<script type="text/javascript"> | |
var cf7wa_ids = <?php echo json_encode( $this->ids ); ?>; | |
var cf7wa_numbers = <?php echo json_encode( $this->numbers ); ?>; | |
var cf7wa_bodies = <?php echo json_encode( $this->bodies ) ?>; | |
(function( $ ){ | |
document.addEventListener( 'wpcf7mailsent', function( event ) { | |
var the_id = event.detail.contactFormId; | |
if( _.indexOf( cf7wa_ids, the_id ) ) { | |
var inputs = event.detail.inputs; | |
var the_text = cf7wa_bodies[the_id]; | |
$.each( inputs, function( index, detail ) { | |
the_text = the_text.replace( '[' + detail.name + ']', detail.value ); | |
} ); | |
the_text = window.encodeURIComponent( the_text ); | |
var the_phone = cf7wa_numbers[ the_id ]; | |
var url = 'https://api.whatsapp.com/send?phone=' + the_phone + '&text=' + the_text; | |
var isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/); | |
var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; | |
if( isSafari && iOS ) { | |
location = url; | |
} else { | |
window.open( url, '_blank' ); | |
} | |
} | |
} ); | |
})(jQuery); | |
</script> | |
<?php endif; | |
$this->script_loaded = true; | |
} | |
} | |
new SP_Contact_Form_WA(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment