Create Post Using A Front Side Form

In this article, We are going to see how to create a post using the front side form.

First of all, create a page template.

Create a page template:

We are using this page template for an HTML form.

<?php
/*
Template Name: Post
*/

Create a HTML form:

<?php
/*
Template Name: Post
*/
  get_header();
?>

<?php				 
$category = get_terms( array(
    'taxonomy' => 'category',
    'hide_empty' => false,
) );
?>
<div class="container">
  <h3 class="text-center py-5">Post Form</h3>
  <form action=" " role="form" id="postform" method="POST" enctype="multipart/form-data">
    <div class="row">
      <div class="col-6">
        <label>Enter Your Post Name :</label>
        <input type='text' name='postname' id='postname'><br>
      </div>
      <div class="col-6">
        <label>Enter Your Post content :</label>
        <input type='text' name='postcontent' id='postcontent'><br>
      </div>
      <div class="col-6">
        <label>Select Your Post Categories :</label><br>
        <?php foreach($category as $cat ){ 
            if( $cat-> parent == 0){ ?>
              <input type="checkbox" id="postcat" name="postcat" value="<?php echo $cat->name ?>">
              <label for="postcat"><?php echo $cat->name ?></label><br>
        <?php	}			
             foreach($category as $sub_cat ) { 
               if($cat->term_id == $sub_cat->parent )	{	?>
                <input type="checkbox" id="postcat" name="postcat" class="sub" value="<?php echo $sub_cat->name ?>">
                <label for="postcat"><?php echo $sub_cat->name ?></label><br>
               <?php } } ?>	
        <?php } ?>
      </div>
    </div>
    <div class="row">
      <div class="col-6">
        <label>Enter Your Post Tages :</label>
        <input type='text' name='posttag' id='posttag'><br>
      </div>
    </div>
    <div class="text-center pt-5">
    <button type="submit" name="submit" value="submit">Submit</button>
    <h4 class='msg pt-3'></h4>
    </div>
  </form>
</div>

Enqueue AJAX Script:

Enqueue ajax script in your theme’s function.php file.

function add_ajax_script() {
   wp_localize_script( 'ajax-js', 'ajax_params', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'add_ajax_script' );

Create AJAX Call:

In this, we insert the post data using an AJAX call in WordPress posts.

jQuery(document).ready(function(event) {

  jQuery("#postform").on('submit',function(event) {
    event.preventDefault();
  
    var postname = jQuery('#postname').val();
    var postcontent = jQuery('#postcontent').val();
    var test = [];
    jQuery("input[name='postcat']:checked").each(function() {
      test.push(jQuery(this).val());
    });
    var posttag = jQuery('#posttag').val();
    
    if( postname == '' && postcontent == '' ){
      alert("Please Fill Out All Of The Fields");
    }else {
      jQuery.ajax({
        method: 'POST',
        url: ajaxurl, 
        data:  {
          'action' : 'post_create_ajax_request', 
          'postname' : postname,
          'postcontent' : postcontent,
          'postcat' : test,
          'posttag' : posttag
        }, 
        success:function(data) {
          jQuery('.msg').html('Successfully Submited Post...');
        },
        error: function(errorThrown){
          window.alert(errorThrown);
        }
      }); 
    }
    });
});

Insert The Post Data:

Create a function which is a call in ajax action and this function is used to insert data in the backend.

In this, data insert a using wp_insert_post() function.

function post_create_ajax_request(){
  
  $cat_id = [];
  $category = $_POST['postcat'];
  foreach( $category as $cat ){
    $cat_id[] = get_cat_ID($cat);
  }
  
  $title = $_POST['postname'];
  $content = $_POST['postcontent'];
  
  $value = $_POST['posttag'];
  $arrayval = explode(",",$value); 

  $post = array(
      'post_title' => $title,		
      'post_content' => $content,
      'post_status'   => 'publish',
      'post_category' => $cat_id,
      'tags_input' => $arrayval
  );
  $post_id = wp_insert_post($post); 
}
add_action( 'wp_ajax_post_create_ajax_request', 'post_create_ajax_request' );
add_action( 'wp_ajax_nopriv_post_create_ajax_request', 'post_create_ajax_request' );

Output:

Thank You, hope you guys found something useful.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories