I am building a user generated content sharing theme
so how can i allow visitors to upload an image from a url
i mean to say that they enter the url and the image gets automatically attached
this is the code i am currently using for
<?php
/*
Template Name: Submit Content Template
*/
// if you are not using this in a child of Twenty Eleven, you need to replicate the html structure of your own theme.
get_header(); ?>
<div id="primary">
<div id="content" role="main">
<?php
if(isset($_POST['new_post']) == '1') {
$post_title = $_POST['post_title'];
$post_category = 'todays_post';
$post_content = $_POST['post_content'];
$tags = $_POST['post_tags'];
$new_post = array(
'ID' => '',
'post_author' => $user->ID,
'post_category' => array($post_category),
'post_content' => $post_content,
'tags_input' => array($tags),
'post_title' => $post_title,
'post_category' => array($_POST['cat']), //
'post_status' => '',
'post_type' => 'post',
'winerating' => $winerating
);
$post_id = wp_insert_post($new_post);
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, $post_id );
}
}
if ($attach_id > 0){
$post = get_post($post_id,'ARRAY_A');
$image = wp_get_attachment_image_src( $attach_id, 'large' );
$image_tag = '<p><a href="'.$image[0].'" rel="lightbox" title="<?php the_title();?>" >
<img src="'.$image[0].'" width="'.$image[1].'" height="'.$image[2].'" /></a></p>';
//add image under the content
$post['post_content'] = $image_tag . $post['post_content'];
//add image above the content
//$post['post_content'] = $post['post_content'] . $image_tag;
$post_id = wp_update_post( $post );
}
// Update Custom Meta
// This will redirect you to the newly created post
$post = get_post($post_id);
wp_redirect( get_permalink($post_id));
exit();
}
?>
UPDATE #1
<?php
/*
Template Name: Submit Content Template
*/
// if you are not using this in a child of Twenty Eleven, you need to replicate the html structure of your own theme.
get_header(); ?>
<div id="primary">
<div id="content" role="main">
<?php
if(isset($_POST['new_post']) == '1') {
$post_title = $_POST['post_title'];
$post_category = 'todays_post';
$post_content = $_POST['post_content'];
$tags = $_POST['post_tags'];
$winerating = $_POST['winerating'];
$new_post = array(
'ID' => '',
'post_author' => $user->ID,
'post_category' => array($post_category),
'post_content' => $post_content,
'tags_input' => array($tags),
'post_title' => $post_title,
'post_category' => array($_POST['cat']), //
'post_status' => 'publish',
'post_type' => 'post',
'winerating' => $winerating
);
$post_id = wp_insert_post($new_post);
// Only for outside WP Theme; if you have this in a file you will need to load "wp- load.php" to get access to WP functions. If you post to "self" with this code then WordPress is by default loaded
require $_SERVER['DOCUMENT_ROOT'] . "/wp-load.php";
// require two files that are included in the wp-admin but not on the front end. These give you access to some special functions below.
require $_SERVER['DOCUMENT_ROOT'] . "/wp-admin/includes/file.php";
require $_SERVER['DOCUMENT_ROOT'] . "/wp-admin/includes/image.php";
// required for wp_handle_upload() to upload the file
$upload_overrides = array( 'test_form' => FALSE );
global $current_user;
get_currentuserinfo();
$logged_in_user = $current_user->ID;
// count how many files were uploaded
$count_files = count( $_FILES['files'] );
// load up a variable with the upload direcotry
$uploads = wp_upload_dir();
// foreach file uploaded do the upload
foreach ( range( 0, $count_files ) as $i ) {
// create an array of the $_FILES for each file
$file_array = array(
'name' => $_FILES['files']['name'][$i],
'type' => $_FILES['files']['type'][$i],
'tmp_name' => $_FILES['files']['tmp_name'][$i],
'error' => $_FILES['files']['error'][$i],
'size' => $_FILES['files']['size'][$i],
);
// check to see if the file name is not empty
if ( !empty( $file_array['name'] ) ) {
// upload the file to the server
$uploaded_file = wp_handle_upload( $file_array, $upload_overrides );
// checks the file type and stores in in a variable
$wp_filetype = wp_check_filetype( basename( $uploaded_file['file'] ), null );
// set up the array of arguments for "wp_insert_post();"
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/.[^.]+$/', '', basename( $uploaded_file['file'] ) ),
'post_content' => '',
'post_author' => $logged_in_user, // or use a static ID
'post_status' => 'publish',
'post_type' => 'attachment',
'post_parent' => $_POST['post_id'],
'guid' => $uploads['baseurl'] . '/' . $file_array['name']
);
// insert the attachment post type and get the ID
$attachment_id = wp_insert_post( $attachment );
// generate the attachment metadata
$attach_data = wp_generate_attachment_metadata( $attachment_id, $uploaded_file['file'] );
// update the attachment metadata
wp_update_attachment_metadata( $attachment_id, $attach_data );
// this is optional and only if you want to. it is here for reference only.
// you could set up a separate form to give a specific user the ability to change the post thumbnail
// set_post_thumbnail( $_POST['post_id', $attachment_id );
}
}
$post_id = wp_update_post( $post );
// Update Custom Meta
// This will redirect you to the newly created post
$post = get_post($post_id);
wp_redirect( get_permalink($post_id));
exit();
}
?>
<html>
<head>
<title>Add Your Funny Pics</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var blank="http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif";
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev')
.attr('src', e.target.result)
.height(100);
};
reader.readAsDataURL(input.files[0]);
}
else {
var img = input.value;
$('#img_prev').attr('src',img).height(200);
}
$("#x").show().css("margin-right","10px");
}
$(document).ready(function() {
$("#x").click(function() {
$("#img_prev").attr("src",blank);
$("#x").hide();
});
});
</script>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
#x { display:none; position:relative; z-index:200; float:right}
#previewPane { display: inline-block; }
</style>
<meta charset=utf-8 />
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<p>
<span style="font-family:comic sans ms,cursive;"><span style="color: rgb(105, 105, 105);"><span style="font-size: 24px;"><strong>Add a Funny Pic</strong></span></span> </span></p><br />
<!----------<Upload Bar>----->
<span style="font-size:12px;">Pic File :- </span>
<div style="position:relative;float:right;margin-top: -88px;"><span id="previewPane">
<img id="img_prev" src="#" alt="your image" />
<span id="x">[X]</span></div></div>
<br />
<fieldset>
<!----------</Upload Bar>----->
<br /> <br />
<!----------<Post Title>----->
<span style="font-size:12px;">Post Title :- </span><input type="text" required="required" name="post_title" size="60" id="input-title" placeholder="Add A Title Here" class="rounded" />
<br>
<!----------</Post Title>----->
<br/>
<!--<post tags>-->
<fieldset class="tags">
<label for="post_tags">
<span style="font-size:12px;">Tags :- </span></label>
<input type="text" class="rounded" placeholder="Add Some Tags To Get Higher Votes"value="" size="60" tabindex="35" name="post_tags" id="post_tags" />
</fieldset>
<!--</post tags>-->
</br>
<!-- <post Category> -->
<fieldset class="category">
<label for="cat">
<span style="font-size:12px;">Category   </span></h4></label><?php wp_dropdown_categories( 'tab_index=10&taxonomy=category&hide_empty=0' ); ?>
</fieldset>
<!-- </post Category> -->
<span style="font-size:12px;">Text Area</span></h4><br />
<textarea rows="5" name="post_content" cols="66" id="text-desc" ></textarea><br>
<input type="hidden" name="new_post" value="1" /> <br>
<div style="Float:right;"><input class="submitbutton" type="submit" name="submit" value="Add" /><br><br></div>
</form>
</body>
</div></div></div>
<!--// New Post Form -->
<?php get_footer(); ?>
You have not created the attachment as link to the post, you will need to do that first. Then you can use in the content.
Alternative it is possibel to upload to other path, but better is a link in the post, post-ID to attachment-ID.
Easiest way to do that is with
wp_insert_attachment()
. This function takes an array of a few parameters, the filename (the file must already be in the proper uploads directory), and the post ID of the parent post that you want to attach the attachment to.You find different answers here for this topic; like 40301
Edit #1:
At first the field for th upload in form for the follow example:
<input type="file" name="files[]" multiple>
And now the workflow for upload the attachments:
See Codex for the example in
media_handle_sideload
function.