Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I want to use a Regular Expression(regex) to test the value of a form's zipcode field on a WordPress page, then based upon those results either:

  • Selectively assign/reveal price fields on the same page.

    or

  • Selectively redirect user to a page having the result-specific pricing.

Here's the regex and the js pseudo-code skeleton.

var  zip5 = event.value.toString();

var myRegExp = /^92(2|3|5)/;

if ( zip5.length === 5 && myRegExp.test(zip5))
{
    // Code to assign/display price set #1 on same page...or
    // Code to move to Wordpress Page with Price Set #1
}
else
{
    // Code to assign/display price set #2 on same page...or
    // Code to move to Wordpress Page with Price Set #2
}
share|improve this question
add comment

2 Answers

I think you've more or less got what you need. You've got a textfield in an HTML form. That form needs to sit in a template file somewhere in a WordPress theme. This template file generates uncached pages.

Inside the PHP template for said template file, check the $_POST (or $_REQUEST) object for the form field ID you've set in the HTML. Then do your templating logic in the kind of if..else logic block you outline in psudeocode above.

if( isset( $_POST['form_field_id'] ) && validation_function( $_POST['form_field_id'] ) ) {
  //stuff to display to validated zipcodes   
} else {
  //stuff to display to non-validated zipcodes
}

Your validation function can probably go anywhere, but is likely most accessable via functions.php:

function validation_function($text_to_validate) {
   $validation_result = [preg_match][2]("/^92(2|3|5)/",$text_to_validate);
   if( count( $validation_result ) > 1 ) {
      return true;
   } else {
      return false;
   }
}
share|improve this answer
add comment

There's a problem with your regex - it will match a string of "92" then 2, 3 or 5, but the last two characters can be anything - including letters. You're not specifying digits for the regex. You probably want something like

var myRegExp = /^92(2|3|5)\d+$/;

Also, you need to make a decision as to whether you want to do this in PHP or Javascript - you can't do both, unless you're using an AJAX call to retrieve the price. (There's no reason to do it twice anyways.) @editor's script looks right (apart from the regex not checking for digits) for a PHP solution, but by your description, it sounds like you're looking for a Javascript solution.

If you opt for the Javascript pricing and actually have the prices in the source of the code, you might end up with some pissed off people wondering why they're paying more for the same item than someone from a different zip code.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.