Home Forums Front-end Issues Attach images created in front end form to custom post Reply To: Attach images created in front end form to custom post

  • Hi @tsmulugeta
    Wow, I do not remember when I last used this function as I resorted to using the repeater fields extension. However, If my memory serves me right, my goal was to create a new post of a custom type and attach an image to it, and not the page that the front end form was generated on. To save the post, this is the code I “think” i placed in my functions.php file to save the custom post. If it helps, I was using this code for a simple online classifieds website to post ads:

    function my_pre_save_post( $post_id )
        // check if this is to be a new post
        if( $post_id != 'new' )
            return $post_id
        // Create a new post
        $ad = array(
            'post_status'    => 'published',
            'post_content'   => $_POST['description'],
            'post_title'     => $_POST['title'],
            'post_type'      => 'ads',
            'post_author'    => get_current_user_id(),
            'comment_status' => 'closed',   // if you prefer
            'ping_status'    => 'closed'    // if you prefer
        // insert the post
        $post_id = wp_insert_post( $ad ); 
        // set post (ad) terms
        $category = intval( $data['category'] );
        wp_set_object_terms( $post_id, array( $category ), 'ad-categories' );
        wp_set_object_terms( $post_id, explode( ',', $data['tags'] ), 'ad-tags' );
        // now this is where I retrieved the submitted image id
        // from the form and attached it to the post
        attachment_change_parent( $_POST['ad_image'], $post_id );    
        // return the new ID
        return $post_id;
    add_filter('acf/pre_save_post' , 'my_pre_save_post', 10, 1 );
    // this function changes the parent of the attached image to the post
    function attachment_change_parent($aid,$pid) {
    	global $wpdb;
    	$query = "UPDATE {$wpdb->prefix}posts
    		SET post_parent = $pid
    		WHERE ID = $aid";
    	return ($wpdb->query( $wpdb->prepare($query) )) ? true : false;

    Basically, from the front end form, as soon as the image is uploaded (via javascript), it’s attached to the page on which the form resides, but what I did was during the “pre_save_post” hook, I get the submitted image id and change the id of the page it’s attached to to the post as soon as the post is created.

    I hope this makes some sense and I sure hope it points you into finding a solution. I am here in case you need any more explanation with anything.

    Thank you!