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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.
