Advertisement
Creative Coding

Creating Nifty Petitions Inside Your Posts

by

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!

Related Posts
  • Code
    PHP
    Validation and Exception Handling: From the UI to the BackendProcedural to oop php retina preview
    Sooner or later in your programming career you will be faced with the dilemma of validation and exception handling. This was the case with me and my team also. A couple or so years ago we reached a point when we had to take architectural actions to accommodate all the exceptional cases our quite large software project needed to handle. Below is a list of practices we came to value and apply when it comes to validation and exception handling.Read More…
  • Code
    Plugins
    Displaying Information of a WordPress.org Plugin on Your WebsiteWordpressdotorg plugin api border 400
    In the first part of this article, we discussed how to use built-in functions to communicate with WordPress.org and retrieve plugin details. In this tutorial we will put the theory in action to create a simple plugin which will allow us to display details of any plugin hosted on WordPress.org on our WordPress website using shortcodes.Read More…
  • Code
    Plugins
    Create a Shortcode to List Posts With Multiple ParametersPost listing shortcode main image400
    On many of the client sites I build, I find there are times when I need to include a post listing on a page. I'm not talking about archive pages here, but adding a custom listing to an existing static page. For example, I might want to list some posts on the 'About' page, or the site may require an in-depth page for a topic, with a list of posts and custom post types related to that topic. One way to do this is by creating a custom page template to include the current page content plus the results of a second custom query, but if you want more flexibility over how you list posts, or just want to do it a few times, a shortcode will be a simpler solution. In this tutorial, I'll show you how to create a simple shortcode to list all posts of a custom post type, and then I'll expand on that to create a shortcode with various parameters that users can specify to list posts however they want.Read More…
  • Code
    Plugins
    Integrating Multiple Choice Quizzes in WordPress – Creating the FrontendIntegrating multiple choice quizzes in wordpress
    This is the second part of the series on developing a multiple choice quiz plugin for WordPress. In the first part we created the backend of our plugin to capture the necessary data to store in the database. In this final part, we will be creating the frontend of the plugin where the users can take quizzes and evaluate their knowledge.Read More…
  • Code
    Plugins
    Multiple Shortcodes With a Single Function: 3 Killer ExamplesMultiple shortcodes with a single function 3 killer examples
    The powerful Shortcode API allows us to create "snippets" and include special content (such as PHP functions or complex HTML code) in our posts. It's extremely common to build separate functions for each shortcode, but is it really necessary? In this post, we're going to see how we can utilize more than one shortcode by building a single function.Read More…
  • Code
    Creative Coding
    Creating a Simple Contact Form for Simple NeedsSimple contact shortcode 200
    Whether you're starting a simple blog, creating a corporate website or building a creative portfolio with WordPress, a "Contact (Us)" page is (almost) always necessary and it's (almost) always better to have a contact form instead of sharing your e-mail address publicly (spam robots love them, though). Of course, there are plenty of great contact form plugins for WordPress but why bloat up the website with heavy plugins with lots of database queries, when we can use just a lovely, simple custom shortcode plugin instead?Read More…