I need a help in correcting my code that can front end post or attach image or post&attach image ;)
Now I can send a 'post' and 'post with photo' but can't send just a photo, How can I do that? who can help in this please.
Here is the code
<?php
if ('POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST['action']) && $_POST['action'] == 'post') {
// Do some minor form validation to make sure there is content
if ($_POST['post_content'] != '') {
$post_content = $_POST['post_content'];
} else {
wp_redirect(get_bloginfo('url') . '/');
exit ;
}
check_admin_referer('new-post');
$user_id = $current_user -> user_id;
$post_content = $_POST['post_content'];
$char_limit = 40;
$post_title = strip_tags($post_content);
if (strlen($post_title) > $char_limit) {
$post_title = substr($post_title, 0, $char_limit) . ' ... ';
}
$tags = $_POST['post_tags'];
//Cas as array
$terms = isset($_POST['category']) ? (array)$_POST['category'] : array();
//Cast array values as integers if $_POST['offer'] contains IDs
$terms = array_map('intval', $terms);
$post_id = wp_insert_post(array('post_author' => $user_id, 'post_title' => $post_title, 'post_content' => $post_content, 'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags), 'post_type' => $_POST['post_type'], // Use a custom post type if you want to,
'post_status' => 'publish', ));
if (!function_exists('wp_generate_attachment_metadata')) {
require_once (ABSPATH . "wp-admin" . '/includes/image.php');
require_once (ABSPATH . "wp-admin" . '/includes/file.php');
require_once (ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES) {
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
$attach_id = media_handle_upload($file, $post_id);
}
}
if ($attach_id > 0) {
//and if you want to set that image as Post then use:
update_post_meta($post_id, '_thumbnail_id', $attach_id);
echo "uploaded the new Thumbnail";
}
wp_redirect(get_bloginfo('url') . '/');
exit ;
}
?>
And my html post form is
<form id="new_post" name="new_post" method="post" enctype="multipart/form-data" action="<?php bloginfo('url'); ?>" style="width:95%; margin:auto;">
<input type="hidden" name="action" value="post" >
<?php wp_nonce_field('new-post'); ?>
<div>
<input type="hidden" name="post_type" id="post_type"/>
<?php wp_editor('', 'post_content', $settings = array('tinymce' => false, 'wpautop' => true, 'teeny' => true, 'media_buttons' => false, 'quicktags' => false, 'strip_tags' => false, 'textarea_name' => 'post_content',; ?>
</div>
<input type="file" name="attachment" id="attachment" style="display: none;" >
