Diwakar Academy

  • Home
  • WordPress
  • About Us
  • Contact Us
You are here: Home / WordPress / How to Submit Custom Post Type in WordPress from the Front End

June 6, 2022

How to Submit Custom Post Type in WordPress from the Front End

Spread the love

Submit custom post type in WordPress from the front end and allow your visitors a way to submit some kind of content of their own, then here’s a way you can create a new custom post type form and display it

Table of Contents

Toggle
  • Submit Custom Post Type in WordPress from the Front End
    • Step 1. Create a new folder for your plugin
  • Step 2. Register Custom Post Type
  • Step 3. Register Custom taxonomy
  • Step 4. Add custom meta box
  • Step 5. Add or Rename column name
  • Step. 6 Sorting data according to column
  • Step 7. Create a form by which a user can submit the custom post type
  • Step 8. Create css file and enqueue
  • Full code index.php file

In this post, we are going to explain how to insert or add custom posts from the front end. Inserting custom post type post from front end in WordPress is important functionality. This is very simple and common process.

WordPress allow to users add custom post type functionality using WordPress dashboard. Author, Admin and contributor user can be submit post if you looking logged in used don’t use dashboard and add post from front end then you just follow simple these steps.

Submit Custom Post Type in WordPress from the Front End

Step 1. Create a new folder for your plugin

First of you should create a folder and giving it a unique name using lowercase letters and dashes. My plugin folder name is “books”. After create folder need to create the main file for your plugin. So, create a PHP file within your plugin folder and give it the same name such as books.php or index.php file.

<?php
/*
*Plugin Name: Submit custom post type from frontend
*Description: My plugin to explain the submit custom post type from frontend functionality. 
*Version: 1.0
*Author: Diwakar Academy
*Author URI: https://diwakaracademy.com/
*/

Step 2. Register Custom Post Type

add_action('init','register_custom_post_types');

function register_custom_post_types(){

	register_post_type('book',

		[
			'labels' => [

				'name' => 'Books',
				'singular_name' => 'Book',
				'menu_name' => 'Books',
			],
			'public' => true,
			'publicly_queryable' => true,
			'menu_icon' => 'dashicons-book',
			'has_arvhive' => true,
			'rewrite' => ['slug' => 'book'],
			'supports' => [
				'title',
				'editor',
				'thumbnail',
			],
		]

	);
}

Step 3. Register Custom taxonomy

function register_taxonomies(){


	register_taxonomy('book_category', ['book'],[


		'hierarchical' => true,
		'labels' => [
			'name' => 'Categories',
			'singular_name' => 'Category',
			'menu_nam' => 'Categories',
		],
		'show_ui' => true,
		'show_admin_column' => true,
		'rewrite' => ['slug'=>'cat']

	]

	);

}

add_action('init','register_taxonomies');

Step 4. Add custom meta box

function custom_meta_boxes(){

	add_meta_box('book_cpt_id','ISBN No.','book_cpt_callback_func','book','normal','low');

}

add_action('add_meta_boxes','custom_meta_boxes');


function book_cpt_callback_func(){ 

	wp_nonce_field('basename(__FILE__)','wp_book_cpt_nonce');

	$isbn_no = get_post_meta(get_the_ID(),'isbn_no',true);

	?>



	<div>
		<label for="isbn_no">ISBN No.</label>
		<input type="text" name="isbn_no" value="<?php echo $isbn_no; ?>">
	</div>
<?php 
}

add_action('save_post','custom_cpt_save_meta_box',10, 2);

function custom_cpt_save_meta_box($post_id, $post){

	if(!isset($_REQUEST['wp_book_cpt_nonce']) || wp_verify_nonce($_REQUEST['wp_book_cpt_nonce'], basename(__FILE__))){
		return;

	}

	if('book' != $post->post_type){
		return;
	}

	if(isset($_REQUEST['isbn_no'])){

		$isbn_no = sanitize_text_field($_REQUEST['isbn_no']);
		update_post_meta($post_id,'isbn_no',$isbn_no);
	}

}

Step 5. Add or Rename column name

add_action('manage_book_posts_columns','book_custom_cpt_columns');

function book_custom_cpt_columns(){

	$custom_columns = [
		'cb' => '<input type="checkbox">',
		'title' => 'Book Title',
		'isbn_no' => 'ISBN No',
		'book_cat' => 'Categories',
		'date' => 'Date',

	];


	return $custom_columns;
}

add_action('manage_book_posts_custom_column','book_cpt_custom_column_data',10,2);

Step. 6 Sorting data according to column

add_filter('manage_edit-book_sortable_columns','book_cpt_sortable_columns');

function book_cpt_sortable_columns(){
	$columns['title'] = 'title';
	$columns['isbn_no'] = 'isbn_no';
	$columns['book_cat'] = 'book_cat';
    $columns['date'] = 'date';
	return $columns;
}

Step 7. Create a form by which a user can submit the custom post type

Allowing the submission of user custom post from the the front-end of your WordPress site starts with HTML. For us to get the HTML to show up, I am going to use a shortcode in WordPress. Shortcodes are contained in square-brackets, and can often be single tags that pull in another PHP function. That’s what we’ll do here, so our form will appear on a post, page, or other WordPress content type when someone uses [book_frontend_post].

add_shortcode('book_frontend_post','book_frontend_post_func');

function book_frontend_post_func(){

	$errors = 0;
	if($_REQUEST['submit'] && wp_verify_nonce($_REQUEST['book_nonce'],'book_action_nonce')){

		if(empty($_REQUEST['title'])){
			$errors++;
		}

		if(empty($_REQUEST['content'])){
			$errors++;
		}

		if(empty($errors)){

			$post = [
				'post_title' => wp_strip_all_tags($_REQUEST['title']),
				'post_content' => $_REQUEST['content'],
				'post_type'=> 'book',
				'post_status' => 'draft',
				'tax_input' => array(
					'book_category' =>$_REQUEST['cat']
				),
			];

			$post_id = wp_insert_post($post);

			if($_REQUEST['isbn_no'])
				update_post_meta($post_id,'isbn_no',$_REQUEST['isbn_no']);
			$filename = $_FILES['image']['name'];
			$file = $_FILES['image']['tmp_name']; 
			if($filename){


				$upload_file = wp_upload_bits( $filename, null, @file_get_contents( $file ) );
				if ( ! $upload_file['error'] ) {
				  // if succesfull insert the new file into the media library (create a new attachment post type).
				  $wp_filetype = wp_check_filetype($filename, null );
				 
				  $attachment = array(
				    'post_mime_type' => $wp_filetype['type'],
				    'post_parent'    => $post_id,
				    'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
				    'post_content'   => '',
				    'post_status'    => 'inherit'
				  );
				 
				  $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $post_id );
				 
				  if ( ! is_wp_error( $attachment_id ) ) {
				     // if attachment post was successfully created, insert it as a thumbnail to the post $post_id.
				     require_once(ABSPATH . "wp-admin" . '/includes/image.php');
				 
				     $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
				 
				     wp_update_attachment_metadata( $attachment_id,  $attachment_data );
				     set_post_thumbnail( $post_id, $attachment_id );
				   }
				}

				unset($_REQUEST['title']);
				unset($_REQUEST['content']);

			}

			if($post_id){
				$msg = "<h5>Saved your post successfully</h5>";
			}
		}

	}

	if(is_user_logged_in()):
?>


	<div class="postbox">
		<?php echo $msg; 


		if($errors): ?>
			<p style="color:red;">Pleasee fill all the required field</p>
		<?php endif; ?>	
		<form method="post" enctype="multipart/form-data">
			<p><label for="title">Book Title *</label><br>
			   <input type="text" value="<?php echo $_REQUEST['title']; ?>" name="title">
			</p>
			<p><label for="content">Book Content *</label><br>
			   <textarea name="content" rows="6"><?php echo $_REQUEST['content']; ?></textarea>
			</p>
			<p><label>Category *</label><br>
			  	<?php wp_dropdown_categories('show_option_none=Category&taxonomy=book_category&hide_empty=0'); ?>
			</p>
			<p><label for="tags">ISBN No</label><br>
			   <input type="text" name="isbn_no">
			</p>
			<p><label for="title">Featured Image</label><br>
			   <input type="file" name="image">
			</p>
			<?php wp_nonce_field("book_action_nonce","book_nonce"); ?>
			<p><input type="submit" name="submit" value="submit">
			</p>
		</form>
	</div>
<?php else: ?>
	<p>After Login you can submit book information</p>

<?php 
endif;
}

Step 8. Create css file and enqueue

If you want to format this form use given css. we need to create css folder with main plugin folder and create a file like style.css

input[type=text], select,textarea {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

input[type=submit] {
  width: 100%;
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

input[type=submit]:hover {
  background-color: #45a049;
}

.postbox {
  border-radius: 5px;
  background-color: #f2f2f2;
  padding: 20px;
  width: 70%;
  margin: 0 auto;
}

wp_enqueue_scripts() function use to enqueue stylesheet and script.

add_action('wp_enqueue_scripts','add_css');

function add_css(){

	wp_enqueue_style('form-css',plugin_dir_url(__FILE__).'/css/form.css');
}

Full code index.php file

<?php
/*
*Plugin Name: Submit custom post type from frontend
*Description: My plugin to explain the submit custom post type from frontend functionality. 
*Version: 1.0
*Author: Diwakar Academy
*Author URI: https://diwakaracademy.com/
*/

add_action('wp_enqueue_scripts','add_css');

function add_css(){

	wp_enqueue_style('form-css',plugin_dir_url(__FILE__).'/css/form.css');
}


add_action('init','register_custom_post_types');

function register_custom_post_types(){

	register_post_type('book',

		[
			'labels' => [

				'name' => 'Books',
				'singular_name' => 'Book',
				'menu_name' => 'Books',
			],
			'public' => true,
			'publicly_queryable' => true,
			'menu_icon' => 'dashicons-book',
			'has_arvhive' => true,
			'rewrite' => ['slug' => 'book'],
			'supports' => [
				'title',
				'editor',
				'thumbnail',
			],
		]

	);
}

function register_taxonomies(){


	register_taxonomy('book_category', ['book'],[


		'hierarchical' => true,
		'labels' => [
			'name' => 'Categories',
			'singular_name' => 'Category',
			'menu_nam' => 'Categories',
		],
		'show_ui' => true,
		'show_admin_column' => true,
		'rewrite' => ['slug'=>'cat']

	]

	);

}

add_action('init','register_taxonomies');


function custom_meta_boxes(){

	add_meta_box('book_cpt_id','ISBN No.','book_cpt_callback_func','book','normal','low');

}

add_action('add_meta_boxes','custom_meta_boxes');


function book_cpt_callback_func(){ 

	wp_nonce_field('basename(__FILE__)','wp_book_cpt_nonce');

	$isbn_no = get_post_meta(get_the_ID(),'isbn_no',true);

	?>



	<div>
		<label for="isbn_no">ISBN No.</label>
		<input type="text" name="isbn_no" value="<?php echo $isbn_no; ?>">
	</div>
<?php 
}

add_action('save_post','custom_cpt_save_meta_box',10, 2);

function custom_cpt_save_meta_box($post_id, $post){

	if(!isset($_REQUEST['wp_book_cpt_nonce']) || wp_verify_nonce($_REQUEST['wp_book_cpt_nonce'], basename(__FILE__))){
		return;

	}

	if('book' != $post->post_type){
		return;
	}

	if(isset($_REQUEST['isbn_no'])){

		$isbn_no = sanitize_text_field($_REQUEST['isbn_no']);
		update_post_meta($post_id,'isbn_no',$isbn_no);
	}

}

add_action('manage_book_posts_columns','book_custom_cpt_columns');

function book_custom_cpt_columns(){

	$custom_columns = [
		'cb' => '<input type="checkbox">',
		'title' => 'Book Title',
		'isbn_no' => 'ISBN No',
		'book_cat' => 'Categories',
		'date' => 'Date',

	];


	return $custom_columns;
}

add_action('manage_book_posts_custom_column','book_cpt_custom_column_data',10,2);

function book_cpt_custom_column_data($columns, $post_id){

	switch ($columns) {
		case 'isbn_no':
			echo $isbn_no = get_post_meta($post_id,'isbn_no',true);
			break;

		case 'book_cat':
			$terms = get_the_terms($post_id, 'book_category');
			$out = array();
			if($terms)foreach ($terms as $term)$out[]=$term->name;
			echo join(', ',$out);
			break;	
	}

}

add_filter('manage_edit-book_sortable_columns','book_cpt_sortable_columns');

function book_cpt_sortable_columns(){
	$columns['title'] = 'title';
	$columns['isbn_no'] = 'isbn_no';
	$columns['book_cat'] = 'book_cat';
    $columns['date'] = 'date';
	return $columns;
}

add_shortcode('book_frontend_post','book_frontend_post_func');

function book_frontend_post_func(){

	$errors = 0;
	if($_REQUEST['submit'] && wp_verify_nonce($_REQUEST['book_nonce'],'book_action_nonce')){

		if(empty($_REQUEST['title'])){
			$errors++;
		}

		if(empty($_REQUEST['content'])){
			$errors++;
		}

		if(empty($errors)){

			$post = [
				'post_title' => wp_strip_all_tags($_REQUEST['title']),
				'post_content' => $_REQUEST['content'],
				'post_type'=> 'book',
				'post_status' => 'draft',
				'tax_input' => array(
					'book_category' =>$_REQUEST['cat']
				),
			];

			$post_id = wp_insert_post($post);

			if($_REQUEST['isbn_no'])
				update_post_meta($post_id,'isbn_no',$_REQUEST['isbn_no']);
			$filename = $_FILES['image']['name'];
			$file = $_FILES['image']['tmp_name']; 
			if($filename){


				$upload_file = wp_upload_bits( $filename, null, @file_get_contents( $file ) );
				if ( ! $upload_file['error'] ) {
				  // if succesfull insert the new file into the media library (create a new attachment post type).
				  $wp_filetype = wp_check_filetype($filename, null );
				 
				  $attachment = array(
				    'post_mime_type' => $wp_filetype['type'],
				    'post_parent'    => $post_id,
				    'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
				    'post_content'   => '',
				    'post_status'    => 'inherit'
				  );
				 
				  $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $post_id );
				 
				  if ( ! is_wp_error( $attachment_id ) ) {
				     // if attachment post was successfully created, insert it as a thumbnail to the post $post_id.
				     require_once(ABSPATH . "wp-admin" . '/includes/image.php');
				 
				     $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
				 
				     wp_update_attachment_metadata( $attachment_id,  $attachment_data );
				     set_post_thumbnail( $post_id, $attachment_id );
				   }
				}

				unset($_REQUEST['title']);
				unset($_REQUEST['content']);

			}

			if($post_id){
				$msg = "<h5>Saved your post successfully</h5>";
			}
		}

	}

	if(is_user_logged_in()):
?>


	<div class="postbox">
		<?php echo $msg; 


		if($errors): ?>
			<p style="color:red;">Pleasee fill all the required field</p>
		<?php endif; ?>	
		<form method="post" enctype="multipart/form-data">
			<p><label for="title">Book Title *</label><br>
			   <input type="text" value="<?php echo $_REQUEST['title']; ?>" name="title">
			</p>
			<p><label for="content">Book Content *</label><br>
			   <textarea name="content" rows="6"><?php echo $_REQUEST['content']; ?></textarea>
			</p>
			<p><label>Category *</label><br>
			  	<?php wp_dropdown_categories('show_option_none=Category&taxonomy=book_category&hide_empty=0'); ?>
			</p>
			<p><label for="tags">ISBN No</label><br>
			   <input type="text" name="isbn_no">
			</p>
			<p><label for="title">Featured Image</label><br>
			   <input type="file" name="image">
			</p>
			<?php wp_nonce_field("book_action_nonce","book_nonce"); ?>
			<p><input type="submit" name="submit" value="submit">
			</p>
		</form>
	</div>
<?php else: ?>
	<p>After Login you can submit book information</p>

<?php 
endif;
}

Article by Diwakar Academy / WordPress Leave a Comment

Leave a Reply Cancel reply

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

  • Home
  • WordPress
  • About Us
  • Contact Us

Copyright © 2025 · All Rights Reserved · Terms and Conditions · Privacy Policy