Skip to content

Instantly share code, notes, and snippets.

@petenelson
Created November 16, 2012 15:50
Show Gist options
  • Save petenelson/4088387 to your computer and use it in GitHub Desktop.
Save petenelson/4088387 to your computer and use it in GitHub Desktop.
WordPress: Custom post type (my-document) for docs (PDFs, etc)
<?php
/*
Plugin Name: My Document Permalink
Description: Custom post type (my-document) for docs (PDFs, etc)
Version: 1.0
Author: Pete Nelson
*/
add_action('init', 'my_register_document_post_type');
function my_register_document_post_type()
{
/*
This plugin, in combination with a single-{post-type}.php template, allows you to create a permanent, friendly URL to
a document, and my attaching new media to a post, keep that document updated.
*/
$type_name_s = 'Document';
$type_name_p = 'Documents';
$args = array(
'public' => true,
'labels' => array(
'name' => $type_name_p,
'singular_name' => $type_name_s,
'add_new_item' => 'Add New '. $type_name_s,
'edit_item' => 'Edit ' . $type_name_s,
'new_item' => 'New ' . $type_name_s,
'new_item' => 'View ' . $type_name_s,
'search_items' => 'Search ' . $type_name_p,
'not_found' => 'No ' . $type_name_p . ' found',
'not_found_in_trash' => 'No ' . $type_name_p . ' found in Trash'
),
'description' => 'Documents',
'exclude_from_search' => true,
'show_in_menu' => true,
'capability_type' => 'post',
'has_archive' => true,
'rewrite' => array(
'slug' => 'document',
)
);
register_post_type('my-document', $args);
}
<?php
// gets the most recent attachment for this post
$attachments = get_children(array(
'post_parent' => get_the_id(),
'post_type' => 'attachment',
'numberposts' => 1,
'post_status' => 'any',
'orderby' => 'post_date',
'order' => 'DESC',
)
);
if ($attachments && count($attachments) > 0)
{
$attachment = array_values($attachments);
$attachment = $attachment[0];
$file = get_attached_file($attachment->ID);
// this will output the file directly to the browser, but you may want to redirect
// to the attachment's URL instead
$filesize = filesize($file);
header('Content-Type: ' . $attachment->post_mime_type);
header('Content-Length: ' . $filesize);
header('Content-Disposition: inline; filename=' . basename($file));
ob_clean();
flush();
readfile($file);
}
else {
header("HTTP/1.0 404 Not Found");
}
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment