下面是我用来从前端表单添加帖子的一些代码,该表单还添加元数据和分类术语。请注意,代码段提取了所有安全性、数据验证和数据清理。它只显示了我对数据所做的操作,以便在清理完所有数据后将其添加到数据库中。
// Submit the values if there are no errors
if(empty($errors))
{
// Prepare title
$term = get_term_by(\'id\', $values[\'complaint_type\'], \'complaint-type\');
$title = $values[\'address_clean\'].\' (\'.$term->name.\')\';
// Gather post data
$post = array(
\'post_title\' => $title,
\'post_content\' => $values[\'description\'],
\'post_status\' => \'publish\',
\'post_type\' => PREFIX_POST_TYPE_NAME,
\'post_author\' => 1
);
// Attempt to add post
if($id = wp_insert_post($post))
{
// Add metadata to post
update_post_meta($id, \'_\'.PREFIX_PLUGIN_NAME_L.\'_latitude\', $values[\'latitude\']);
update_post_meta($id, \'_\'.PREFIX_PLUGIN_NAME_L.\'_longitude\', $values[\'longitude\']);
// Associate complaint-type
if(!wp_set_post_terms($id, $values[\'complaint_type\'], \'complaint-type\'))
$errors[\'wp_set_post_terms\'] = \'There was an error adding the complaint type.\';
}
else
$errors[\'wp_insert_post\'] = \'There was an error adding the complaint.\';
}