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 .
<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
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 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 .
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 .
$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.
/* * 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 :
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.
Views: 97