Do you want to allow your visitor to submit contents or articles or news of their own ?
Most of you might be thinking that ‘damn i shall find a plugin for this’, well this is not as hard as you think. You don’t need to search for plugin. Writing code is easier than finding plugin and customizing it.
Follow the following simple steps ;
-
- Create a form with necessary fields i.e. title, content and featured image. Additional field could be : visitor first name, last name , email and category. Don’t forget to add nonce field because it protects the forms from certain types of misuse and malicious .
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182<form id="new_post" class="form-control" name="new_post" method="post" action="" enctype="multipart/form-data"><div class="form-group"><label for="fName">First Name</label><br /><input type="text" id="fName" size="20" class="form-control" name="fName" required value="<?php echo !empty($_POST['fName'])?$_POST['fName']:''; ?>"/></div><div class="form-group"><label for="lName">Last name</label><br /><input type="text" id="lName" size="20" class="form-control" name="lName" required value="<?php echo !empty($_POST['lName'])?$_POST['lName']:''; ?>"/></div><?php$userEmail ="";if(is_user_logged_in()) {$current_user = wp_get_current_user();$userEmail = $current_user->user_email;}if(!empty($_POST['email'])) {$userEmail = $_POST['email'];}?><div class="form-group"><label for="title">email</label><br /><input type="text" id="email" size="20" class="form-control" name="email" required value="<?php echo $userEmail; ?>"/></div><div class="form-group"><label for="title">Title</label><br /><input type="text" id="title" size="20" class="form-control" name="postTitle" value="<?php echo !empty($_POST['postTitle'])?$_POST['postTitle']:''; ?>"/></div><div class="form-group"><label for="content">Post Content</label><br /><textarea id="content" class="form-control" name="content" cols="30" rows="6"><?php echo !empty($_POST['content'])?$_POST['content']:''; ?></textarea></div><div class="form-group"><select class="form-control" name="category"><option>Select Category</option><?php$categories = get_categories( array('hide_empty' => 0,'taxonomy' => 'category','orderby' => 'name','order' => 'ASC') );foreach( $categories as $category ) {echo $_POST['category'];if(!empty($_POST['category']) & ($category->term_id==$_POST['category'])) :$selected = 'selected';else:$selected ='';endif;?><option value="<?=$category->term_id?>" <?=$selected?>><?=$category->name?></option><?php}?></select></div><div class="form-group"><label for="featuredImage">Featured Image:</label><input type="file" class="form-control-file" name="featured" id="featuredImage" size="50"></div><?php wp_nonce_field( 'wp-news-nonce' ); ?><div class="form-group"><input type="submit" value="Publish" id="submit" class="btn btn-primary" name="submit" /></div></form>
- Validate the form fields
1234567891011121314151617181920212223242526272829303132if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST)) {$successMessage = "";$error = [];// Check that the nonce was set and validif( !wp_verify_nonce($_POST['_wpnonce'], 'wp-news-nonce') ) {array_push($error,'Sorry, could not save because your form seemed to be invalid !!');}// Do some minor form validation to make sure there is contentif(empty($_POST['postTitle'])){array_push($error, 'Title is required!');}else if (strlen($_POST['postTitle']) < 5) {array_push($error,' Titles must be at least characters long.');}if(empty($_POST['content'])) {array_push($error, 'Content is required!');}else if (strlen($_POST['content']) < 50) {array_push($error,'Please enter content more than 10 characters in length');}if(empty($_POST['category'])) {array_push($error, 'Category is required!');}if(empty($_POST['email'])){array_push($error, 'Email is required!');}else if(!is_email($_POST['email'])){array_push($error,'invalid email address!');}}
- If the user exists, get the user id ; if the user doesn’t exist, insert the user in the database and get the id of the inserted user . Note : wp_insert_user() gives the user id of just inserted user
- Create a form with necessary fields i.e. title, content and featured image. Additional field could be : visitor first name, last name , email and category. Don’t forget to add nonce field because it protects the forms from certain types of misuse and malicious .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
if(email_exists($email)) { /* check if the user already exist */ $userDetail = get_user_by( 'email', $email); $userID = $userDetail->ID; }else { /* if user doesn't exist create new user and the created user are subscriber*/ $userData = [ 'user_login' => $email, 'user_email' => $email, 'user_pass' => '1234@567', 'first_name' => $fName, 'last_name' => $lName, ]; $userID = wp_insert_user($userData); } |
4. Upload the attached file inside the uploads folder and get the id of the attached file .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$uploadDir = wp_upload_dir(); $file = $_FILES['featured' ]; $uploadFile = $uploadDir['path'] . '/' . basename(sanitize_file_name( $file['name']) ); if (file_exists($uploadFile)) { $uploadFile = $uploadDir['path'] . '/'.time().'-' . basename( sanitize_file_name($file['name'])); } move_uploaded_file( $file['tmp_name'] , $uploadFile ); $filename = basename( $uploadFile ); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', $filename), 'post_content' => '', 'post_status' => 'inherit', 'menu_order' => $_i + 1000 ); $attach_id = wp_insert_attachment( $attachment, $uploadFile ); |
5. Save the contents including featured image in the dashboard . Note : save the contents as a draft so that you can review the post and publish it later.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* * Insert post */ $post = array( 'post_author' => $userID, 'post_title' => $newsTitle, 'post_content' => $_POST['content'], 'post_category' => array($cat), //'tags_input' => array($_POST['post_tags']), 'post_status' => 'draft', // Could be: publish 'post_type' => 'post' // Could be: `page` or your CPT ); $newsID = wp_insert_post($post); /* * set featured image for post */ set_post_thumbnail($newsID, $attach_id ); |
Time for writing the full code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST)) { $successMessage = ""; $error = []; // Check that the nonce was set and valid if( !wp_verify_nonce($_POST['_wpnonce'], 'wp-news-nonce') ) { array_push($error,'Sorry, could not save because your form seemed to be invalid !!'); } // Do some minor form validation to make sure there is content if(empty($_POST['postTitle'])){ array_push($error, 'Title is required!'); }else if (strlen($_POST['postTitle']) < 5) { array_push($error,' Titles must be at least characters long.'); } if(empty($_POST['content'])) { array_push($error, 'Content is required!'); }else if (strlen($_POST['content']) < 50) { array_push($error,'Please enter content more than 10 characters in length'); } if(empty($_POST['category'])) { array_push($error, 'Category is required!'); } if(empty($_POST['email'])){ array_push($error, 'Email is required!'); }else if(!is_email($_POST['email'])){ array_push($error,'invalid email address!'); } if(empty($error)) : // Add the content of the form to $post as an array $userID =""; $email = sanitize_email($_POST['email']); $newsTitle = sanitize_title( $_POST['postTitle']); $fName = sanitize_title( $_POST['fName']); $lName = sanitize_title($_POST['lName']); $cat = sanitize_title($_POST['cat']); /* * Get the user id for post to be inserted */ if(email_exists($email)) { /* check if the user already exist */ $userDetail = get_user_by( 'email', $email); $userID = $userDetail->ID; }else { /* if user doesn't exist create new user and the created user are subscriber*/ $userData = [ 'user_login' => $email, 'user_email' => $email, 'user_pass' => '1234@567', 'first_name' => $fName, 'last_name' => $lName, ]; $userID = wp_insert_user($userData); } /* * Upload Image Attached */ $uploadDir = wp_upload_dir(); $file = $_FILES['featured' ]; $uploadFile = $uploadDir['path'] . '/' . basename(sanitize_file_name( $file['name']) ); if (file_exists($uploadFile)) { $uploadFile = $uploadDir['path'] . '/'.time().'-' . basename( sanitize_file_name($file['name'])); } move_uploaded_file( $file['tmp_name'] , $uploadFile ); $filename = basename( $uploadFile ); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', $filename), 'post_content' => '', 'post_status' => 'inherit', 'menu_order' => $_i + 1000 ); $attach_id = wp_insert_attachment( $attachment, $uploadFile ); /* * Insert post */ $post = array( 'post_author' => $userID, 'post_title' => $newsTitle, 'post_content' => $_POST['content'], 'post_category' => array($cat), 'post_status' => 'draft', // Could be: publish 'post_type' => 'post' // Could be: `page` or any custom post type ); $newsID = wp_insert_post($post); /* * set featured image for post */ set_post_thumbnail($newsID, $attach_id ); $successMessage = 'Saved your post successfully!'; $_POST =[]; endif; if(!empty($successMessage)) { echo '<div class="alert alert-success" role="alert" style="color: green;">'. $successMessage.'</div>'; } else { ?> <div class="alert alert-failure" role="alert" style="color: red;"><?php echo implode('<br/>',$error); ?></div> <?php } } ?> <div id="postbox"> <form id="new_post" class="form-control" name="new_post" method="post" action="" enctype="multipart/form-data"> <div class="form-group"> <label for="fName">First Name</label><br /> <input type="text" id="fName" size="20" class="form-control" name="fName" required value="<?php echo !empty($_POST['fName'])?$_POST['fName']:''; ?>"/> </div> <div class="form-group"> <label for="lName">Last name</label><br /> <input type="text" id="lName" size="20" class="form-control" name="lName" required value="<?php echo !empty($_POST['lName'])?$_POST['lName']:''; ?>"/> </div> <?php $userEmail =""; if(is_user_logged_in()) { $current_user = wp_get_current_user(); $userEmail = $current_user->user_email; } if(!empty($_POST['email'])) { $userEmail = $_POST['email']; } ?> <div class="form-group"> <label for="title">email</label><br /> <input type="text" id="email" size="20" class="form-control" name="email" required value="<?php echo $userEmail; ?>"/> </div> <div class="form-group"> <label for="title">Title</label><br /> <input type="text" id="title" size="20" class="form-control" name="postTitle" value="<?php echo !empty($_POST['postTitle'])?$_POST['postTitle']:''; ?>"/> </div> <div class="form-group"> <label for="content">Post Content</label><br /> <textarea id="content" class="form-control" name="content" cols="30" rows="6"><?php echo !empty($_POST['content'])?$_POST['content']:''; ?></textarea> </div> <div class="form-group"> <select class="form-control" name="category"> <option>Select Category</option> <?php $categories = get_categories( array( 'hide_empty' => 0, 'taxonomy' => 'category', 'orderby' => 'name', 'order' => 'ASC' ) ); foreach( $categories as $category ) { echo $_POST['category']; if(!empty($_POST['category']) & ($category->term_id==$_POST['category'])) : $selected = 'selected'; else: $selected =''; endif; ?> <option value="<?=$category->term_id?>" <?=$selected?>><?=$category->name?></option> <?php } ?> </select> </div> <div class="form-group"> <label for="featuredImage">Featured Image:</label> <input type="file" class="form-control-file" name="featured" id="featuredImage" size="50"> </div> <?php wp_nonce_field( 'wp-news-nonce' ); ?> <div class="form-group"><input type="submit" value="Publish" id="submit" class="btn btn-primary" name="submit" /></div> </form> |
You might not believe, but you have just created the form to allow visitors to add articles/ news/ posts . And the most important part of this form is , you can customize the form without any hassle.
Hits: 59