I want to enable logged in users (Wordpress) to submit posts from front end (among with other data).
My form is working great, I add custom post meta data which I later display on custom post page.
I added enctype="multipart/form-data"
to form tag.
Added this code 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;
}
And this to the custom post page (where the front end form is):
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
};
After this php code I have this code to create post:
$post_information = array(
'post_title' => wp_strip_all_tags( $_POST['title']),
'post_content' => $_POST['content'],
'post_category' => array($_POST['category']),
'post_type' => 'post',
'post_status' => 'pending'
);
$post_information = wp_insert_post($post_information);
add_post_meta($post_information, 'custom1', $_POST['custom1']);
add_post_meta($post_information, 'custom2', $_POST['custom2']);
add_post_meta($post_information, 'custom3', $_POST['custom3']);
Now the post data is added to the new post without problems, and the image is uploaded. I upload image with this:
<input type="file" tabindex="3" name="custom-upload1" id="custom-upload2" />
<input type="file" tabindex="3" name="custom-upload2" id="custom-upload2" />
<input type="file" tabindex="3" name="custom-upload3" id="custom-upload3" />
Now I need to find a way to save and show image on the created custom post. I was thinking about this two options:
- Save the uploaded image URL in a custom field.
- Save image directly to the post.
For my case the first option would be better, but I do not know how to do this.
Is there any way to save like that:
add_post_meta($post_information, 'imageURL', $_POST['imageURL']);
But i do not know how to pass the image URL variable to 'imageURL'.
Is there any option to do that?
__return_false();
will give you the valueFALSE
right there, but it does not return anything back out ofinsert_attachment
.