I have a front-end form which makes a user able to create a post. It only sends title, description and custom fields that are text type. But I also want to add a category option to the form that shows the list of the current categories and makes user to choose one or more of them for their new post. (selected categories will be assigned to the new post.)
It's a WordPress site and I use Avada theme. The custom post type is the Avada's default Portfolio post. But generalised answers would be very helpful too (please give some explanation on your code).
So, Here's my php code in fuctions.php in my child-theme:
if(isset($_POST['title'])){
$custom_field_address1 = $_POST['address1'];
$my_post = array(
'post_title' => $_POST['title'],
'post_content' => $_POST['description'],
'post_status' => 'publish',
'post_type' => 'companies',
'meta_input' => array(
'address1' => $custom_field_address1,
)
);
$post_id = wp_insert_post($my_post);
add_post_meta( $post_id, 'address1', $custom_field_address1, false );
echo 'New Post Saved !';
die;
}
My front-end form (I want to see all of categories for Portfolio post type and choose those I want):
<form method="post">
<div class="form-group">
<label for="title">Post Title:</label>
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="form-group">
<label for="pwd">Post Description :</label>
<textarea class="form-control" name="description"></textarea>
</div>
<div class="form-group">
<label for="address1">Address :</label>
<input type="text" name="address1" id="address1">
</div>
<BR>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I have read many many answers like this, But most of them are just code for another person's site with too little explanations. So, I need to get more help.