Home > OS >  Auto-select fields in Contact form 7 based on referral link
Auto-select fields in Contact form 7 based on referral link

Time:12-10

I have been using this answer by Aurovrata ( Wordpress Contact Form 7 dynamically select dropdown field based on url )in order to get what I wanted.

My script is looking like this:

(function($){
$(document).ready(function(){

  //determine the previous page,
  let page = document.referrer, opt='';


  switch(true){
    case page.indexOf('service-b')>0:
      opt='serviceb';
      break;
    case page.indexOf('service-c')>0:
      opt='servicec';
      break;
    case page.indexOf('service-a')>0:
      opt='servicea';
      break;
  }

  $('select[name="select-services"]').find('option[value="' opt '"]').prop('selected', 'selected');
})
})(jQuery) 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="select-services">
 <option value="">select a service</option>
 <option value="servicea">Service A</option>
 <option value="serviceb">Service B</option>
 <option value="servicec">Service C</option>
</select> 

The result is that the right service is selected for one second and after that is going back to the default. Any idea what I'm doing wrong?

PS: In order to get it done, I have added this script in function.php to prevent the CF7 resetting the form:

add_action('wpcf7_enqueue_scripts', 'prefix_fix_form_reset');

function prefix_fix_form_reset() {
    $wpcf7 = array();
    wp_localize_script( 'contact-form-7', 'wpcf7', $wpcf7 );
}

CodePudding user response:

You have extra parentheses in your JS code but other than that it works. Are you sure the page referrer for the third service contains the correct slug service-c?

Option A:

Here is a demo: https://jsfiddle.net/9z5m4syd/2/

Updated JS code:

$(document).ready(function() {
  // determine the previous page
  // eg. page referrer
  let page = 'http://website.domain/service-c', opt='';

  switch(true){
    case page.indexOf('service-b')>0:
      opt='serviceb';
      break;
    case page.indexOf('service-c')>0:
      opt='servicec';
      break;
    case page.indexOf('service-a')>0:
      opt='servicea';
      break;
  }
// Run this after 1.5 seconds
setTimeout(function() {
  $('select[name="select-services"]').find('option[value="' opt '"]').prop('selected', 'selected');
}, 1500);

})(jQuery);

Option B:

Create a custom form tag and select the course server-side.

New form tag: [courses your-field-name]

Add to functions.php:

/**
 * Register a new CF7 form tag.
 * 
 * Use this tag in your form [courses your-field-name]
 */
add_action( 'wpcf7_init', 'custom_add_form_tag_courses' );

function custom_add_form_tag_courses() {
    wpcf7_add_form_tag( array( 'courses', 'courses*' ), 'custom_courses_form_tag_handler', true );
}

/**
 * CF7 callback function that parses the form tag.
 */
function custom_courses_form_tag_handler( $tag ) {

    $tag = new WPCF7_FormTag( $tag );

    if ( empty( $tag->name ) ) {
        return '';
    }

    $custom_select = '';
    $option        = '';

    // Retrieve referer from ‘_wp_http_referer’ or HTTP referer.
    $page_refferer = wp_get_referer();

    // List of courses.
    $courses = array(
        "Alege cursul",
        "CURS MAKEUP",
        "CURS EXTENSII GENE",
        "CURS STILIST PROTEZIST UNGHII",
        "CURS COSMETICA",
        "CURS MASAJ",
        "CURS DESIGN INTERIOR",
        "CURS FRIZERIE/BARBERING",
        "CURS MANICHIURIST PEDICHIURIST",
        "CURS DECORATOR FLORAL",
        "CURS EPILARE",
        "CURS FOTOGRAFIE",
        "CURS VIDEO",
        "CURS MICRONEEDLING",
        "CURS COAFOR",
        "CURS DE EXTENSII PAR",
        "CURS COLORIMETRIE",
        "CURS CROITORIE",
        "CURS STILISM VESTIMENTAR",
        "CURS CONSTRUCTIE TIPARE",
        "WORKSHOP STILIZARE SPRANCENE",
        "WORKSHOP COMBI DRY MANICURE",
        "WORKSHOP AUTO COAFAT",
        "WORKSHOP IMPLETITURI"
    );
 
    // Loop through all the courses and create option values.
    foreach( $courses as $course ) {
        
        // Generate course slug.
        $slug = sanitize_title( $course );

        // Search for course in page refferer.
        $match = stripos( $page_refferer, $slug );

        // Check if refferer exists and compare it to the course list.
        if ( ! empty( $page_refferer ) && $match !== false ) {
            $option .= sprintf( '<option value="%1$s" selected="selected">%2$s</option>', esc_html( $slug ), esc_html( $course ) );
        } else {
            $option .= sprintf( '<option value="%1$s">%2$s</option>', esc_html( $slug ), esc_html( $course ) );     
        }
    }

    // Add previously generated list of options to the select tag.
    $custom_select = sprintf( '<select name="%1$s" id="%2$s">%3$s</select>', $tag->name, esc_attr( $tag->name . '-options' ), $option );

    return $custom_select;
}
  • Related