0

i have a form that allows input of name ,email & photo...when i click on submit i want it to insert a row into the posttype called'contact' with the info submitted by the form and the image as the featured image but it does not set the image as featured image

my code

<?php

 if (isset($_POST['submit'])) {    

     $yourname=$_POST['yourname'];
     $email=$_POST['email'];
     $myimage=$_POST['myimage'];    

$my_post = array(
 'post_title' => $youname, 
 'post_status' => 'publish',
 'post_author' => 1,
 'post-thumbnails' => $myimage
);
$post_id = wp_insert_post( $my_post );
if ($_FILES) {
    foreach ($_FILES as $file => $array) {
    $imageid = insert_attachment($file,$pid);    
    }
}
set_post_thumbnail($post_id,$imageid);
update_field( "field_5507c9", $email, $post_id );   
}   
?>

<form action="" method="POST">
         Your Name: <input type="text" name="yourname" value=""> <br>
         Your Email:  <input type="text" name="email" value=""> <br>
         Image: <input type="file" name="myimage" id=""><br>    
        <input type="submit" name="submit" value="submit" />           
</form>

add this below to functions.php

function insert_attachment($file_handler,$post_id,$setthumb='false') {
    // check to make sure its a successful upload
    if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $attach_id = media_handle_upload( $file_handler, $post_id );

    if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
    return $attach_id;
}

plus is there any way i can check if row is uploaded & echo a message if insert is done and then redirect to a new url after few seconds.

-1

first of all you need to add enctype="multipart/form-data" to make your form support file uploads.

So far you've attached the image to the post, but you haven’t inserted them. Try something like this

<?php 
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' =>   null, 'post_parent' => $post->ID );  
$attachments = get_posts($args);  
if ($attachments) { 
    foreach ( $attachments as $attachment ) { ?>

    <?php echo apply_filters( 'the_title' , $attachment->post_title ); ?>

    <?php the_attachment_link( $attachment->ID , false ); ?>

<?php }  
}
?>
  • 1
    Adding a code snippet and explaining why that is needed in the form would help the author more than just saying "do this". – Welcher Mar 18 '15 at 4:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.