Skip to content
This repository has been archived by the owner on Sep 28, 2023. It is now read-only.

Headline testing via Experiment API #1

Merged
merged 19 commits into from
May 16, 2014
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 37 additions & 40 deletions admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,73 +17,70 @@ function optimizely_plugin_action_links( $links, $file ) {
add_filter( 'plugin_action_links', 'optimizely_plugin_action_links', 10, 2 );

function optimizely_conf() {
global $optimizely_nonce;
global $optimizely_nonce, $DEFAULT_VARIATION_TEMPLATE;


if ( isset($_POST['submit']) ) {
if ( function_exists('current_user_can') && !current_user_can('manage_options') )
die(__('Cheatin’ uh?'));

check_admin_referer( $optimizely_nonce );
$project_code = htmlentities(stripslashes($_POST['project_code']));

$token = $_POST['token'];
$project_id = $_POST['project_id'];
$project_name = stripcslashes($_POST['project_name']);
$project_code = stripcslashes($_POST['project_code']);
$variation_template = stripcslashes($_POST['variation_template']);

if ( empty($token) ) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just as a head's up, "empty" in PHP is rather inclusive. The following are considered empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

Just makes sure this jibes with what you want to do here.

delete_option('optimizely_token');
} else {
update_option('optimizely_token', $token);
}

if ( empty($project_id) ) {
delete_option('optimizely_project_id');
} else {
update_option('optimizely_project_id', $project_id);
}

if ( empty($project_name) ) {
delete_option('optimizely_project_name');
} else {
update_option('optimizely_project_name', $project_name);
}

if ( empty($project_code) ) {
$ms = 'new_code_empty';
delete_option('optimizely_project_code');
} else {
update_option('optimizely_project_code', $project_code);
$ms = 'new_code_saved';
}

if ( empty($variation_template) ) {
update_option('optimizely_variation_template', $DEFAULT_VARIATION_TEMPLATE);
} else {
update_option('optimizely_variation_template', $variation_template);
}

echo "<div id='message' class='updated fade'><p><strong>Settings saved.</strong></p></div>";

}

$messages = array(
'new_code_empty' => 'Your project code has been cleared. Please enter a new project code to use Optimizely on this site.',
'new_code_saved' => 'Your project code has been saved. Enjoy using Optimizely!',
'code_empty' => 'Please enter your project code.'
);
?>
<?php if ( !empty($_POST['submit'] ) ) : ?>
<div id="message" class="updated fade">
<p>
<?php _e('<strong>Configuration saved.</strong><br \>'.$messages[$ms]) ?>
</p>
</div>
<?php endif; ?>
<div class="wrap">
<h2><?php _e('Optimizely Configuration'); ?></h2>
<div class="narrow">
<form action="" method="post" id="optimizely-conf">
<h3>About Optimizely</h3>
<p>Simple, fast, and powerful. <a href="http://www.optimizely.com" target="_blank">Optimizely</a> is a dramatically easier way for you to improve your website through A/B testing. Create an experiment in minutes with our easy-to-use visual interface with absolutely no coding or engineering required. Convert your website visitors into customers and earn more revenue today!</p>
<h3>Register now</h3>
<p>Create an account at <a href="http://www.optimizely.com" target="_blank">optimizely.com</a> and start A/B testing today! After creating an account you can come back to this configuration page and set up your WordPress website to use Optimizely.</p>
<h3>Optimizely project code</h3>
<p>You can find your project code on your project's experiments page. Go to <a href="https://www.optimizely.com/experiments">optimizely.com/experiments</a>, make sure you've selected the right project and click on &lt;Project Code&gt;, then click on 'Copy to Clipboard'. You can then paste the code in the box below. Your project code should start with "&lt;script" and end with "&lt;/script&gt;".</p>
<label for="project_code" style="font-weight:bold;">Paste your project code</label>
<input id="project_code" name="project_code" type="text" size="60" maxlength="80" value="<?php echo get_option('optimizely_project_code'); ?>" style="font-family: 'Courier New', Courier, mono; font-size: 1.5em;" />
<?php optimizely_nonce_field($optimizely_nonce) ?>
<p class="submit"><input type="submit" name="submit" value="<?php _e('Update configuration &raquo;'); ?>" /></p>
</form>
</div>
</div>
<?php
include(dirname( __FILE__ ) . '/config.php');

}

function optimizely_admin_warnings() {
if ( !get_option('optimizely_project_code') && !isset($_POST['submit']) ) {
function optimizely_warning() {
echo "
<div id='optimizely-warning' class='updated fade'><p><strong>".__('Optimizely is almost ready.')."</strong> ".sprintf(__('You must <a href="%1$s">enter your Optimizely project code</a> to begin using Optimizely on your site.'), "admin.php?page=optimizely-config")."</p></div>";
<div id='optimizely-warning' class='updated fade'><p><strong>".__('Optimizely is almost ready.')."</strong> ".sprintf(__('You must <a href="%1$s">authenticate and choose a project</a> to begin using Optimizely on your site.'), "admin.php?page=optimizely-config")."</p></div>";
}
add_action('admin_notices', 'optimizely_warning');
return;
}
}

function optimizely_admin_menu() {
optimizely_load_menu();
}

function optimizely_load_menu() {
add_submenu_page('plugins.php', __('Optimizely Configuration'), __('Optimizely Configuration'), 'manage_options', 'optimizely-config', 'optimizely_conf');
}
33 changes: 33 additions & 0 deletions config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
function optimizelyConfigPage() {
var $ = jQuery;

// Select a project ID
$('#project_id').change(function() {
var id = $('#project_id').val();
var name = $('#project_id option:selected').text();
var project_code = '<script src="//cdn.optimizely.com/js/' + id + '.js"></script>';
$('#project_code').text(project_code);
$('#project_name').val(name);
});

// Get list of projects
$("button#connect_optimizely").click(function(event) {
event.preventDefault();
$("#project_id").html("<option>Loading projects...</option>");

optly = new OptimizelyAPI($("#token").val());

optly.get('projects', function(response) {
$("#project_id").empty();

$.each(response, function(key, val) {
$("#project_id").append("<option value='" + val.id + "'>" + val.project_name + "</option>");
});

$("#project_id").change();
});



});
}
48 changes: 48 additions & 0 deletions config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<div class="wrap">
<h2><?php _e('Optimizely Configuration'); ?></h2>
<div class="narrow">
<form action="" method="post" id="optimizely-conf">
<?php optimizely_nonce_field($optimizely_nonce) ?>
<h3>About Optimizely</h3>
<p>Simple, fast, and powerful. <a href="http://www.optimizely.com" target="_blank">Optimizely</a> is a dramatically easier way for you to improve your website through A/B testing. Create an experiment in minutes with absolutely no coding or engineering required. Convert your website visitors into customers and earn more revenue: create an account at <a href="http://www.optimizely.com" target="_blank">optimizely.com</a> and start A/B testing today!</p>
<h3>Optimizely API tokens</h3>
<p>Once you create an account, you can find your API Token on your account page at <a href="https://www.optimizely.com/account">optimizely.com/account</a>.
<p>
<label for="token"><strong>API Token</strong></label>
<br />
<input id="token" name="token" type="text" maxlength="80" value="<?= get_option('optimizely_token'); ?>" class="code" />
</p>

<button id="connect_optimizely" class="button">Connect Optimizely</button>

<h3>Choose a Project</h3>
<input type="hidden" id="project_name" name="project_name" value="<?= get_option('optimizely_project_name') ?>" />
<select id="project_id" name="project_id">
<?php if (get_option('optimizely_project_id')) { ?>
<option value="<?= get_option('optimizely_project_id') ?>" selected><?= get_option('optimizely_project_name') ?></option>
<?php } ?>
<option value="">Connect Optimizely to choose a project...</option>
</select>
<p>Optimizely will add the following project code to your page automatically:</p>
<textarea class="code" id="project_code" name="project_code" readonly><?= get_option('optimizely_project_code') ?></textarea>


<h3>Variation Code</h3>
<p>Optimizely will use this variation code to change headlines on your site. We've provided code that works with the default theme, but you might want to add or change it to work with your themes and plugins.</p>

<textarea class="code" rows="5" name="variation_template" id="variation_template"><?= get_option('optimizely_variation_template') ?></textarea>

<p>You can use the variables $POST_ID, $OLD_TITLE, and $NEW_TITLE in your code.</p>

<p class="submit"><input type="submit" name="submit" value="<?php _e('Submit &raquo;'); ?>" class="button-primary" /></p>


</form>
<script type="text/javascript">
optimizelyConfigPage();
</script>



</div>
</div>
165 changes: 165 additions & 0 deletions edit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
function optimizelyEditPage() {
var $ = jQuery;

// Initialize data
var projectId = $('#optimizely_project_id').val();
var optly = new OptimizelyAPI($("#optimizely_token").val());
optly.experiment = {
id: $("#optimizely_experiment_id").val(),
status: $("#optimizely_experiment_status").val()
}

if (optly.experiment.id) {
showExperiment(optly.experiment);
} else {
$('#optimizely_created').hide();
}

$('#optimizely_create').click(function(){
createExperiment();
});

$('#optimizely_toggle_running').click(function(){
if (optly.experiment.status == "Running") {
pauseExperiment(optly.experiment);
} else {
startExperiment(optly.experiment);
}
});

// Render the experiment's state on the page
function showExperiment(experiment) {
// ID and links
$("#optimizely_experiment_id").val(experiment.id);
$('#optimizely_view').attr('href','https://www.optimizely.com/edit?experiment_id=' + experiment.id);
$('#optimizely_results').attr('href','https://www.optimizely.com/results?experiment_id=' + experiment.id);

// Status and buttons
$("#optimizely_experiment_status").val(experiment.status);
$('#optimizely_experiment_status_text').text(experiment.status);
if (experiment.status == "Running") {
$('#optimizely_toggle_running').text('Pause Experiment');
} else {
$('#optimizely_toggle_running').text('Start Experiment');
}

// Hide create button, show status
$('#optimizely_not_created').hide();
$('#optimizely_created').show();

// Update Wordpress backend w/ experiment data
var data = {
action: "update_experiment_meta",
post_id: $('#post_ID').val(),
optimizely_experiment_id: experiment.id,
optimizely_experiment_status: experiment.status
};

$('.optimizely_variation').each(function(index, input) {
data[$(input).attr('name')] = $(input).val();
});
$.post(wpAjaxUrl, data);
}

function createExperiment() {
$('#optimizely_create').text('Creating...');

experiment = {};
experiment.description = "Wordpress: " + $('#title').val();
experiment.edit_url = $('#sample-permalink').text();

optly.post('projects/' + projectId + '/experiments', experiment, onExperimentCreated);
}

function onExperimentCreated(experiment) {

optly.experiment = experiment;

var variations = $('.optimizely_variation').filter(function(){return $(this).val().length > 0})

// Set variation weights
var numVariations = variations.length + 1;
var variationWeight = Math.floor(10000 / numVariations);
var leftoverWeight = 10000 - variationWeight*numVariations;

// Create variations
variations.each(function(index, input) {
var weight = variationWeight + (index == 0 ? leftoverWeight : 0);
createVariation(experiment, index + 1, $(input).val(), weight);
});

// Create goal
createGoal(experiment);

}

function createGoal(experiment) {

var goal = {
goal_type: 3, // pageview goal
title: "Views to page",
urls: [$('#sample-permalink').text()],
url_match_types: [4], // substring
// addable: false, // don't clog up the goal list
experiment_ids: [experiment.id]
}

optly.post('projects/' + experiment.project_id + '/goals/', goal, checkExperimentReady);

}

function createVariation(experiment, index, newTitle, weight) {

// Generate variation code
var variationTemplate = $('#optimizely_variation_template').val();
var postId = $('#post_ID').val();
var originalTitle = $('#title').val();
var code = variationTemplate
.replace(/\$OLD_TITLE/g, originalTitle)
.replace(/\$NEW_TITLE/g, newTitle)
.replace(/\$POST_ID/g, postId);

// Request data
var variation = {
"description": newTitle,
"js_component": code,
"weight": weight,
}

// Update variation #1, create the others
if (index == 1) {
optly.patch('variations/' + experiment.variation_ids[1], variation, checkExperimentReady);
} else {
optly.post('experiments/' + experiment.id + '/variations', variation, checkExperimentReady);
}

}

function checkExperimentReady(response) {
if (optly.outstandingRequests == 0) {
showExperiment(optly.experiment);
}
}

function startExperiment(experiment) {
$('#optimizely_toggle_running').text('Starting...');
optly.patch('experiments/' + experiment.id, {'status': 'Running'}, function(response) {
optly.experiment = response;
showExperiment(optly.experiment);
});
}

function pauseExperiment(experiment) {
$('#optimizely_toggle_running').text('Pausing...');
optly.patch('experiments/' + experiment.id, {'status': 'Paused'}, function(response) {
optly.experiment = response;
showExperiment(optly.experiment);
});
}

}





Loading