Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function abtest($name, $A , $B , $C = false , $D = false ) {
- session_start();
- $array_options = array();
- $array_options['A']= $A;
- $array_options['B']= $B;
- if($C != false) {
- $array_options['C']= $C;
- }
- if($D != false) {
- $array_options['D']= $D;
- }
- if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
- return $array_options[$A]; // if bot then don't allow data sqew - returns first value to allow rendering / page function - usage & goal data not stored. As A is often the original method testing it means the original page is served up.
- } else {
- $data = get_post_meta(1 , 'ABtest-' . $name , true);
- if(empty($data)) {
- $data = array();
- foreach($array_options as $key => $option) {
- $data[$key]= array( 'served' => '1' , 'goals' => '1');
- }
- }
- if(mt_rand(0,99) <= 23) { // percent of random serving. In practice found with mt_rand that around 20-25% is a good amount to help ofsetting the nature of "randomness", ensuring a decent enough mix is served up for actually testing the different options.
- $serve = array_rand($array_options);
- $_SESSION['ABtest-' . $name] = $serve;
- } else {
- $best = 0;
- foreach ($data as $key => $option) {
- $Shown = $option['served'];
- $Goals = $option['goals'];
- $curr = $Goals / $Shown;
- if($curr > $best) {
- $serve = $key;
- $best = $curr;
- }
- }
- }
- $data[$serve]['served']++;
- update_post_meta(1 , 'ABtest-' . $name , $data);
- $_SESSION['ABtest-' . $name] = $serve;
- return $array_options[$serve];
- }
- }
- function abtestGoalHit($name , $value) {
- if(!empty($_SESSION['ABtest-' . $name])) {
- $Served = $_SESSION['ABtest-' . $name];
- $data = get_post_meta(1 , 'ABtest-' . $name , true);
- $data[$Served]['goals'] = $data[$Served]['goals'] + $value;
- update_post_meta(1 , 'ABtest-' . $name , $data);
- }
- }
- function resetABtest($name) {
- $metakey = 'ABtest-' . $name;
- return delete_post_meta(1, $metakey);
- }
- ########
- $orange = 'orange';
- $apple = 'apple';
- $pear = 'pear';
- $straw = 'strawberry';
- if(isset($_POST['conversion'])) {
- abtestGoalHit('fruitchoice' , 1);
- } else if(isset($_POST['conversion2'])) {
- abtestGoalHit('fruitchoice' , 2);
- } else if(isset($_POST['clear'])) {
- delete_post_meta(1 , 'ABtest-fruitchoice');
- unset($_SESSION['ABtest-fruitchoice']);
- die;
- }
- ?>
- <h1>My fave fruit...</h1>
- <p>I love <?php echo abtest('fruitchoice' , $orange , $apple , $pear , $straw); ?> the most</p>
- <form method="post">
- <input name="conversion" type="submit" value="I agree!" />
- <input name="conversion2" type="submit" value="I couldn't agree more" />
- <input name="clear" type="submit" value="Clear!" />
- </form>
- <a href="">No / Bounce</a>
Add Comment
Please, Sign In to add comment