1

I'm using this code to submit a post form and upload an image which I want as the post thumbnail. Everything submits perfectly and the image even uploads but I can't seem to figure out how to attach the image to the post and set it as the post thumbnail automatically. Any help would be greatly appreciated.

<?php

$postContentError = '';

if ( isset( $_POST['submitted'] ) && isset( $_POST['post_nonce_field'] ) && wp_verify_nonce( $_POST['post_nonce_field'], 'post_nonce' ) ) {

if ( trim( $_POST['postContent'] ) === '' ) {
    $postContentError = 'Please enter a description of this property.';
    $hasError = true;
}

$random = rand(1000000, 9999999);

$post_information = array(      
    'post_name' => sanitize_title( date( 'YmdHis' ). '-' . $random),
    'post_title' => 'Property '.date( 'YmdHis' ). '-' . $random,
    'post_content' => $_POST['postContent'],
    'post_type' => 'properties',
    'post_status' => 'publish'
);

$propertyfor = $_POST['propertyfor'];
$propertytype = $_POST['propertytype'];
$bedrooms = $_POST['bedrooms'];

$post_id = wp_insert_post($post_information);

function upload_user_file( $file = array() ) {
      require_once( ABSPATH . 'wp-admin/includes/admin.php' );
      $file_return = wp_handle_upload( $file, array('test_form' => false ) );
      if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
          return false;
      } else {
          $filename = $file_return['file'];
          $attachment = array(
              'post_mime_type' => $file_return['type'],
              'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
              'post_content' => '',
              'post_status' => 'inherit',
              'guid' => $file_return['url']
          );
          $attachment_id = wp_insert_attachment( $attachment, $file_return['url'], $post_id );
          require_once(ABSPATH . 'wp-admin/includes/image.php');
          $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
          wp_update_attachment_metadata( $attachment_id, $attachment_data );
          if( 0 < intval( $attachment_id ) ) {
                return $attachment_id;
          }
      }
      return false;
}

if( ! empty( $_FILES ) ) {
  foreach( $_FILES as $file ) {
    if( is_array( $file ) ) {
      $attachment_id = upload_user_file( $file );
    }
  }
}

if($post_id) {
    // Update Custom Meta
    update_post_meta($post_id, 'shru_price', esc_attr(strip_tags($_POST['shru_price'])));
    update_post_meta($post_id, 'shru_address', esc_attr(strip_tags($_POST['shru_address'])));

    wp_set_object_terms( $post_id, $propertyfor, 'propertyfor' );
    wp_set_object_terms( $post_id, $propertytype, 'propertytype' );
    wp_set_object_terms( $post_id, $bedrooms, 'bedrooms' );

    // Redirect
    wp_redirect(home_url('/listings'));
    exit;
}

}

?>
  • 1
    we would need more information to be able to help, for instance, are the images being uploaded from the frontend or admin side? whats wrong with using the featured image system already built in. – Firestorm_dev Apr 6 '14 at 11:03
  • I'm building a front end form. Not sure how to use the built-in system so I just found tutorials to code it instead. This is my input file field: <input type="file" id="thumbInput" name="thumbInput" required="required" /> – CoreyRS Apr 6 '14 at 11:09
  • oh cool, you could have a look at this plugin,(wordpress.org/plugins/frontend-uploader) , perhaps you could break down the source code and see how they achieved it or try these links: (wpquestions.com/question/showChrono/id/8856) (code.tutsplus.com/tutorials/…) – Firestorm_dev Apr 6 '14 at 11:41
1

You have a variable scope problem.

$post_id = wp_insert_post($post_information);

function upload_user_file( $file = array() ) {
      require_once( ABSPATH . 'wp-admin/includes/admin.php' );
      $file_return = wp_handle_upload( $file, array('test_form' => false ) );
      // ...

You set $post_id outside of your upload_user_file() function but that means that it is unavailable inside the function where you need it for wp_insert_attachment().

If you had debugging enabled as you should when working, you would have spotted that immediately.

Additionally, you are including a couple of core files-- for example, require_once( ABSPATH . 'wp-admin/includes/admin.php' );-- which nearly always indicates that you are Doing it Wrong. I have a feeling that you should be using the AJAX API instaed of, what I am guessing you are doing, loading a "handler" file directly.

  • how would I fix this? i'm not the greatest PHP coder – CoreyRS Apr 6 '14 at 22:32
  • It doesnt need to use ajax as I just use the html5 fileAPI to display the image and I would rather the system not upload the file automatically if the user then changes their mind about it. – CoreyRS Apr 6 '14 at 22:45
  • ok, set global $post_id inside the function and have now been able to attach the image to the post. now to crack setting the thumbnail... – CoreyRS Apr 7 '14 at 1:14
  • sorted! thanks for pointing me in the right direction! – CoreyRS Apr 7 '14 at 1:20

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.