existWordPress Theme CustomizationIn the process, there are many times when you need the front-end form function, if it is a relatively simple function, you can use the comment form to achieve, but encountered a form with more fields, with the comment system to achieve more trouble, such as the following form.
Need fields and WordPress comment fields are different, then how do we realize this form? Many friends will think of using plug-ins, this is not an efficient and convenient way, the above form is achieved through the visual form builder plug-in, but the plug-ins will bring performance and security issues, can not use plug-ins to achieve a customized form?
How do we implement a custom form without using a plugin?
WordPress provides a rich enough API for us to use, today we are here to talk about not using plug-ins to achieve custom form implementation ideas. The main WordPress features to be used are wp_insert_post
respond in singing update_post_meta
The
Step 1: Create the HTML form
There's not much to say about this step, and it's easy enough for anyone who knows HTML to do.
Step 2: Set the variables to receive the data sent from the HTML form
The main code used is as follows, with as many form items as there are new variables.
$ask_title = isset( $_POST['ask_title'] ) ? $_POST['ask_title'] : '';
This step has no technical content, not more long-winded, save some time to hurry to the point.
Step 3: Data validation
if ( empty($ask_title) || strlen($ask_title) > 20 ){
wp_die('Nickname must be filled in, no more than 20 characters long');;
}
Step 4:Save data to custom post types and custom fields
Here's the kicker. wp_insert_post and update_post_meta are used here.
// First create a new post object
$my_post = array(
'post_title' => $ask_title //this is the title field that was submitted by the form, the
'post_content' => 'This is the content customization',
'post_status' => 'publish', //post status
'post_category' => array(8,39) //category id, can be used to differentiate between forms
);
$new_post = wp_insert_post( $my_post ); //Insert the post into the database, if successful, return the id of the newly created post
update_post_meta($new_post, 'custom field id', $ask_data); //Insert custom field to the newly created post id
At this point, the work of building custom forms is complete, of course, this is only a very basic function, if you want to go to the next level, you can look at: