Collect user input from front end and store into a custom post WordPress.

This Codes will create a form for the front-end users to collect data and store the data into a custom post. Shortcode is also made to use the form anywhere.

 

1. Create a custom post type: You can create a custom post type in WordPress by using the register_post_type() function in your theme’s functions.php file or in a custom plugin.

Function.php

function create_custom_post_type() {
register_post_type(
‘my_custom_post_type’,
array(
‘labels’ => array(
‘name’ => __(‘My Custom Post Type’),
‘singular_name’ => __(‘My Custom Post’),
),
‘public’ => true,
‘has_archive’ => true,
‘supports’ => array(‘title’, ‘editor’, ‘thumbnail’),
)
);
}
add_action(‘init’, ‘create_custom_post_type’);

 

2. Create a front-end form: You can create a front-end form using HTML and PHP to collect user input.

index.php

<form method=”post”>
<label for=”title”>Title:</label>
<input type=”text” name=”title” id=”title”><br>

<label for=”content”>Content:</label>
<textarea name=”content” id=”content”></textarea><br>

<input type=”submit” name=”submit” value=”Submit”>
</form>

3. Process the form submission: Once the user submits the form, you can process the submission using PHP and store the data in the custom post type

if (isset($_POST[‘submit’])) {
$title = sanitize_text_field($_POST[‘title’]);
$content = wp_kses_post($_POST[‘content’]);

$post_id = wp_insert_post(array(
‘post_title’ => $title,
‘post_content’ => $content,
‘post_type’ => ‘my_custom_post_type’,
‘post_status’ => ‘publish’,
));

if ($post_id) {
echo ‘Post created successfully.’;
} else {
echo ‘Error creating post.’;
}
}

 

SHORTCODE

1. Create a custom post type and front-end form as described in the previous answer.

2. Add the following code to your theme’s functions.php file or a custom plugin to create a shortcode for the form:

function my_custom_post_form_shortcode() {
ob_start();
?>
<form method=”post”>
<label for=”title”>Title:</label>
<input type=”text” name=”title” id=”title”><br>

<label for=”content”>Content:</label>
<textarea name=”content” id=”content”></textarea><br>

<input type=”submit” name=”submit” value=”Submit”>
</form>
<?php

if (isset($_POST[‘submit’])) {
$title = sanitize_text_field($_POST[‘title’]);
$content = wp_kses_post($_POST[‘content’]);

$post_id = wp_insert_post(array(
‘post_title’ => $title,
‘post_content’ => $content,
‘post_type’ => ‘my_custom_post_type’,
‘post_status’ => ‘publish’,
));

if ($post_id) {
echo ‘Post created successfully.’;
} else {
echo ‘Error creating post.’;
}
}

return ob_get_clean();
}
add_shortcode(‘my_custom_post_form’, ‘my_custom_post_form_shortcode’);

 

3.Save the file and go to the page where you want to display the form. Add the shortcode [my_custom_post_form] to the page content or text widget.

Leave a Comment