Linear Circuit

<?php
add_action('post_edit_form_tag', 'post_edit_form_tag');
function post_edit_form_tag() {
echo ' enctype="multipart/form-data"';
}
function custom_field_document_upload() {
global $post;

$custom = get_post_custom($post->ID);
$download_id = get_post_meta($post->ID, 'document_file_id', true);

echo '

Upload document:
‘;
echo ‘

‘;
echo ‘

‘;

if(!empty($download_id) && $download_id != ‘0’) {
echo ‘


View document

‘;
}
}
function custom_field_document_update($post_id) {
global $post;

if(strtolower($_POST[‘post_type’]) === ‘page’) {
if(!current_user_can(‘edit_page’, $post_id)) {
return $post_id;
}
}
else {
if(!current_user_can(‘edit_post’, $post_id)) {
return $post_id;
}
}

if(!empty($_FILES[‘document_file’])) {
$file = $_FILES[‘document_file’];
$upload = wp_handle_upload($file, array(‘test_form’ => false));
if(!isset($upload[‘error’]) && isset($upload[‘file’])) {
$filetype = wp_check_filetype(basename($upload[‘file’]), null);
$title = $file[‘name’];
$ext = strrchr($title, ‘.’);
$title = ($ext !== false) ? substr($title, 0, -strlen($ext)) : $title;
$attachment = array(
‘post_mime_type’ => $wp_filetype[‘type’],
‘post_title’ => addslashes($title),
‘post_content’ => ”,
‘post_status’ => ‘inherit’,
‘post_parent’ => $post->ID
);

$attach_key = ‘document_file_id’;
$attach_id = wp_insert_attachment($attachment, $upload[‘file’]);
$existing_download = (int) get_post_meta($post->ID, $attach_key, true);

if(is_numeric($existing_download)) {
wp_delete_attachment($existing_download);
}

update_post_meta($post->ID, $attach_key, $attach_id);
}
}
}
?>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s