Your logic is a little flawed – you run isset
checks on fields like title
and description
, but don’t actually halt the post insertion if they’re not set.
You also don’t check the post_tags
index, which will never exist because wp_dropdown_categories
will use the field name cat
unless you set it to something else.
Not to mention that tags_input
is specifically for the taxonomy post_tag
, so even if everything else was working, the terms would never be properly assigned.
Let’s refactor and use the PHP filter API while we’re at it:
<?php
if ( 'POST' === $_SERVER['REQUEST_METHOD'] && filter_input( INPUT_POST, 'action' ) === 'new_post' ) {
$errors = [];
$title = filter_input( INPUT_POST, 'title', FILTER_SANITIZE_STRING );
$description = filter_input( INPUT_POST, 'description', FILTER_SANITIZE_STRING );
if ( ! $title ) {
$errors[] = 'Please enter a title';
}
if ( ! $description ) {
$errors[] = 'Please enter a description';
}
if ( ! $errors ) {
$new_post_id = wp_insert_post([
'post_title' => $title,
'post_content' => $description,
'post_status' => 'draft',
'post_type' => 'books',
]);
if ( ! $new_post_id ) {
$errors[] = 'Oops, something went wrong';
} else {
/**
* Loop over taxonomies and attempt to set post terms.
*/
foreach ([
'books-categories',
'location',
'services_c',
] as $post_taxonomy ) {
// Field name is the format "{taxonomy}_term_id"
if ( $term_id = ( int ) filter_input( INPUT_POST, "{$post_taxonomy}_term_id" ) ) {
wp_set_object_terms( $new_post_id, $term_id, $post_taxonomy );
}
}
}
}
foreach ( $errors as $error ) {
echo "$error<br />";
}
}
Now we just need to set the right input name
for each taxonomy dropdown – I’ve used the format {taxonomy}_term_id
so as not to confuse WordPress (if you used just the taxonomy name as the input, it will likely clash with the query_var
for said taxonomy).
wp_dropdown_categories( 'name=books-categories_term_id&show_option_none=Category&tab_index=4&taxonomy=books-categories' );
Do the same for the others and you should be good to go.