Advertisement

Creating Nifty Petitions Inside Your Posts

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

WordPress is a great multi-purpose platform. You can create many websites with many different purposes: a corporate website, a photography showcase, a news portal, a restaurant website with interactive menus... Oh, and blogs, of course. You can blog with WordPress. Forgot about that.

Strangely, non-profit organizations tend to overlook this flexibility and take advantage of it. In this tutorial, we're going to show how to create a simple petition script to demonstrate how an organization can benefit from WordPress.


What Are We Building, Exactly?

I'm a huge fan of shortcodes (as you can see from my previous posts), so we're going to make a bunch of shortcodes and some helpful functions for the shortcodes to use. We're going to get all of these together in a file called petition.php and use it as a WordPress plugin.


Helper Functions

Since we're going to use them inside our shortcodes, I thought it would be better to create and explain them first.

A Basic E-Mail Validating Function

If you're using PHP5 on your server, we're going to use the built-in e-mail validators for our function:

// e-mail address validating function
function validate_email( $email ) {
	if ( $email == '' ) {
		return false;
	} else {
		return filter_var( $email, FILTER_VALIDATE_EMAIL );
	}
}

And if you're using something ancient like PHP4, you can use a different function which makes use of regular expressions:

// e-mail address validating function
function validate_email( $email ) {
	if ( $email == '' ) {
		return false;
	} else {
		$eregi = preg_replace( '/([a-z0-9_.-]+)' . '@' . '([a-z0-9.-]+){2,255}' . '.' . '([a-z]+){2,10}/i', '', $email );
	}
	return empty( $eregi ) ? true : false;
}

Please Note: You can't use both!

The Function to Submit the Entries

We could create and use a different database table to contain the petitions' submissions but I don't think that it's a good practice. And hey, what's wrong with custom fields?

// submit the signer with a 'petition_submission' meta key to the post
function submission( $name, $email, $date ) {
	global $post;
	$array = array( 'name' => $name, 'email' => $email, 'date' => $date );
	$petition_meta = serialize( $array );
	add_post_meta( $post->ID, 'petition_submission', $petition_meta );
	return true;
}

As you can read from the code;

  • We took the $name, $email and $date variables into the function (from the shortcode which we'll get to in a minute)
  • Put the three variables together by creating an array and serializing it
  • And saved the data as a custom field named 'petition_submission'

Simple, right? Now we can get to the kinda-hard part.

The Function to Fetch the Submissions

We can now save the submissions but how will we get them and do stuff with them? Here's how:

// fetch the submissions from the post
function get_the_submissions( $number = 5 ) {
	$petition_meta = get_post_custom_values( 'petition_submission' );
	if ( $petition_meta ) {
		$output = array_slice( $petition_meta, $number * -1 );
		return array_reverse( $output );
	}
}

Remember when I said it's going to be kinda-hard? I lied:

  • We assigned the values of the post metas with the 'petition_submission' key to an array variable
  • Then we got $number (5 by default) of submissions from the end of the array (notice the -1)
  • And we returned the reversed list of that sliced array to order it newest to oldest

Extra: CSS Selectors to Use

We'll be using some CSS selectors in the code, so put them in your style.css file of your theme:

#petition_form {}
#petition_form label {
	font-weight: bold;
	font-size: larger;
	line-height: 150%;
}
#petition_form input {
	display: block;
	margin: 5px 0;
	padding: 3px;
}
#petition_name {
	width: 200px;
}
#petition_email {
	width: 200px;
}
#petition_submit {
	padding: 5px;
}
.petition_success {
	color: #693;
}
.petition_error {
	color: #A00;
}
.petition_list {
	list-style: none;
	margin: 0;
	padding: 0;
}
.petition_list li {
	background-image: none !important;
}
.petition_list span {
	display: inline-block;
	width: 45%;
	padding: 1%;
	margin: 1%;
	background-color: #FAFAFA;
}
.submission_name {}
.submission_date {
	font-style: italic;
	color: #888;
}

Feel free to edit the default values of the properties :)


Shortcodes

We completed the helper functions and the CSS code. Now, let's get to the fun part - the shortcodes!

We could do with just one big shortcode to attach the form, list the entries and show the number of submissions but... why kill all the fun? Besides, separate shortcodes for these three elements would liberate us to use them wherever we want in our content.

Did I tell you how I love shortcodes?

The Shortcode for the Petition Form

This function is a long one, so I'm going to explain the code inside the code, with PHP comments:

function petition_form_sc( $atts ) {
	// extract the shortcode parameters
	extract( shortcode_atts( array(
		// the text value of the submit button
		'submit' => 'Submit',
		// the text for the error message
		'error' => 'Your e-mail address is not valid. Please re-enter the form with a valid name and e-mail address.',
		// the text when the submission is successful
		'success' => 'Your submission has been saved. Thank you!'
	), $atts ) );

	// the HTML elements of our petition form
	$form = '<form action="'.get_permalink().'" method="post" id="petition_form">
		<label for="petition_name">Name:</label>
		<input type="text" name="petition_name" id="petition_name" />
		<label for="petition_email">E-mail address:</label>
		<input type="text" name="petition_email" id="petition_email" />
		<input type="submit" name="petition_submit" id="petition_submit" class="submit" value="'.$submit.'" />
	</form>';

	// if the form is "POST"ed...
	if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
		// ...get the name...
		$name = $_POST['petition_name'];
		// ...and the e-mail address...
		$email = $_POST['petition_email'];
		// ...and the date of "just now", with the date format of your WP options.
		$date = date( get_option( 'date_format' ) );
		// validate the e-mail address first!
		if ( validate_email( $email ) == true ) {
			// the e-mail address is valid! remember the function below?
			submission( $name, $email, $date );
			// we sent the variables with the submission() function, now we print the success message WITHOUT THE FORM:
			return '<div class="petition_success">' . $success . '</div>';
			// (if you want the form to be printed again after the submission, just add .$form before the semicolon.)
		} else {
			// the e-mail address is NOT valid! we should print the error message WITH THE FORM:
			return '<div class="petition_error">' . $error . '</div>' . $form;
		}
	}
	// and if the form isn't "POST"ed (meaning the visitor just visited the page), just show the form!
	else {
		return $form;
	}
}
add_shortcode( 'petition_form', 'petition_form_sc' );

I tried to be as clear as I can be but if you believe that I left something out, feel free to ask me by commenting on this post!

The Shortcode for the List of Submissions

The "latest entries" part is the proof that people are joining your cause, so we have to list at least some number of submissions.

This is not a short function either, so I'll explain the code with comments again:

function petition_list_sc( $atts ) {
	// extract the shortcode parameters
	extract( shortcode_atts( array(
		// we could set a default number but remember, we already did that in the get_the_submissions() function :)
		'number' => ''
	), $atts ) );

	// get the $number latest submissions...
	$submissions = get_the_submissions( $number );

	// ...and list 'em!
	$output = '<ul class="petition_list">';
	if ( $submissions ) {
		foreach( $submissions as $submission ) {
			// unserialize the data
			$signer = unserialize( $submission );
			// unserialize the data AGAIN, don't know why...
			$signer = unserialize( $signer );
			// you might want to change this part, but the default format look great with the CSS in this tutorial.
			$output .= '<li>';
			$output .= '<span class="submission_name">' . $signer['name'] . '</span>';
			$output .= '<span class="submission_date">' . $signer['date'] . '</span>';
			$output .= '</li>';
		}
	}
	$output .= '</ul>';

	return $output;
}
add_shortcode( 'petition_list', 'petition_list_sc' );

Again, feel free to ask anything you want to ask by commenting on this post.

The Shortcode for the Petition Count

This is a really small function, just to get how many entries are submitted:

function petition_count_sc() {
	$petition_meta = get_post_custom_values( 'petition_submission' );
	return count( $petition_meta );
}
add_shortcode( 'petition_count', 'petition_count_sc' );

As you can see, it just throws the custom fields to an array and counts it and return the number.


Conclusion

I should emphasize that this is a very simple example to show organizations can benefit from WordPress by utilizing scripts like these. If you can think of an improvement for this script (or tutorial), please share your thoughts in the comments below. Thanks for reading!