I have a simple form that adds a new post and sets a featured image. I am trying to clear the form using this: header("Location: $_SERVER[PHP_SELF]"); but I get a "headers already sent" error message and an "undefined index" after the page reloads.
Notice: Undefined index: attach in /var/www/vhosts/smoige.com/jobs/wp-content/themes/twentyfourteen/page-templates/upload.php on line 20 Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/smoige.com/jobs/wp-includes/post-template.php:478) in /var/www/vhosts/smoige.com/jobs/wp-content/themes/twentyfourteen/page-templates/upload.php on line 53
<?php
/**
* Template Name: Submit
*
* @package WordPress
* @subpackage Twenty_Fourteen
* @since Twenty Fourteen 1.0
*/
get_header(); ?>
<div id="nav-submit-form" style="margin: 0 0 0 333px;">
<span class="nav-submit-form">
<?php
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
if(isset($_POST['submit'])) {
$filename = $_FILES['attach']['name'];
$new_post = array(
'ID' => '',
'post_author' => $current_user->ID,
//'post_category' => array(3322),
'tags_input' => "",
'post_title' => wp_strip_all_tags( $_POST['post_title'] ),
'post_status' => 'publish'
);
$post_id = wp_insert_post($new_post);
$post = get_post($post_id);
$new_post = $post->ID;
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, $new_post );
}
}
if ($attach_id > 0){
//and if you want to set that image as Post then use:
update_post_meta($new_post,'_thumbnail_id',$attach_id);
}
header("Location: $_SERVER[PHP_SELF]");
}
?>
<form method="post" enctype="multipart/form-data" action="" id="upload-form">
<input type="text" name="post_title" value="Image Name" size="45" id="input-title"/>
<input type="file" name="attach" id="image" />
<input id="submitButton" class="subput" type="submit" name="submit" value="Add"/>
</form>
<?php } else {
echo 'Welcome, visitor!';
}
?>
</span>
</div><!-- #nav-submit-form -->
<?php get_sidebar(); get_footer(); ?>