search
HomeBackend DevelopmentPHP TutorialModify your post with a beautiful petition

Modify your post with a beautiful petition

WordPress is a great, versatile platform. You can create a website with many different purposes: a company website, a photography showcase, a news portal, a restaurant website with an interactive menu... Oh, and of course a blog. You can blog using WordPress. forgotten.

Oddly enough, nonprofits often overlook this flexibility and take advantage of it. In this tutorial, we’ll show you how to create a simple petition script that demonstrates how an organization can benefit from WordPress.


What exactly are we building?

I'm a big fan of shortcodes (as you can see from my previous posts), so we're going to make a bunch of shortcodes and some useful functions for shortcodes to use. We will put all of this in a file called petition.php and use it as a WordPress plugin.


Auxiliary functions

Since we are going to use them in shortcodes, I thought it would be best to create and explain them first.

Basic Email Verification Function

If you are using PHP5 on your server, we will use the built-in email validator for our functionality:

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

If you are using something as old as PHP4, you can use different functions that use 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 cannot use both at the same time!

Function to submit entries

We could create and use a different database table to contain the petition submissions, but I don't think this is a good practice. Hey, any problem 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 put the $name, $email and $date variables into the function (from the shortcode we will cover later)
  • Put three variables together by creating an array and serializing it
  • And save the data as a custom field named 'petition_submission'

Pretty simple, right? Now we can get to the somewhat difficult part.

Function to get submission content

We can now save the commits, but how do we get them and do something with them? Methods as below:

// 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 this would be a bit difficult? I lied:

  • We assign the value of the post metadata to the array variable using the "petition_submission" key
  • Then we get $number (default is 5) submissions from the end of the array (note -1)
  • We return a reversed list of this slice array to sort it from newest to oldest

Extra: CSS selectors to use

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

#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 properties :)


Short Code

We have completed the helper functions and CSS code. Now, let’s get to the fun part – shortcodes!

We could just use a big shortcode to attach the form, list the entries and display the number of submissions, but... why kill all the fun? Additionally, separate shortcodes for these three elements will allow us to use them anywhere in our content.

Have I ever told you how I like shortcodes?

Shortcode for petition

This function is quite long, so I will use PHP comments to explain the code Inside :

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 possible, but if you think I'm missing something, feel free to ask me by commenting on this post!

Shortcode for submitting list

The "Latest Entries" section is proof that people are joining your cause, so we must list at least a certain number of submissions.

This is not a short function either, so I will 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, if you have any questions, please leave a comment on this post.

Shortcode for petition count

This is a very small function just to get how many entries were 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 field into an array and counts it and returns the number.


in conclusion

I should emphasize that this is a very simple example of how organizations can benefit from WordPress by leveraging this type of script. If you can think of improvements to this script (or tutorial), please share your thoughts in the comments below. Thank you for reading!

The above is the detailed content of Modify your post with a beautiful petition. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.