最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

customization - Attach pdf file to custom post type

programmeradmin0浏览0评论

I am trying to attach a pdf file to a custom post type.
I have found this snippet at wpsnipp.
The code does the trick, but only for posts.
I have a custom post type named 'events' and I can't make it work.

add_action("admin_init", "pdf_init");
add_action('save_post', 'save_pdf_link');
function pdf_init(){
    add_meta_box("my-pdf", "PDF Document", "pdf_link", "post", "normal", "low");
    }
function pdf_link(){
    global $post;
    $custom  = get_post_custom($post->ID);
    $link    = $custom["link"][0];
    $count   = 0;
    echo '<div class="link_header">';
    $query_pdf_args = array(
            'post_type' => 'attachment',
            'post_mime_type' =>'application/pdf',
            'post_status' => 'inherit',
            'posts_per_page' => -1,
            );
    $query_pdf = new WP_Query( $query_pdf_args );
    $pdf = array();
    echo '<select name="link">';
    echo '<option class="pdf_select">SELECT pdf FILE</option>';
    foreach ( $query_pdf->posts as $file) {
       if($link == $pdf[]= $file->guid){
          echo '<option value="'.$pdf[]= $file->guid.'" selected="true">'.$pdf[]= $file->guid.'</option>';
             }else{
          echo '<option value="'.$pdf[]= $file->guid.'">'.$pdf[]= $file->guid.'</option>';
             }
            $count++;
    }
    echo '</select><br /></div>';
    echo '<p>Selecting a pdf file from the above list to attach to this post.</p>';
    echo '<div class="pdf_count"><span>Files:</span> <b>'.$count.'</b></div>';
}
function save_pdf_link(){
    global $post;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){ return $post->ID; }
    update_post_meta($post->ID, "link", $_POST["link"]);
}
add_action( 'admin_head', 'pdf_css' );
function pdf_css() {
    echo '<style type="text/css">
    .pdf_select{
            font-weight:bold;
            background:#e5e5e5;
            }
    .pdf_count{
            font-size:9px;
            color:#0066ff;
            text-transform:uppercase;
            background:#f3f3f3;
            border-top:solid 1px #e5e5e5;
            padding:6px 6px 6px 12px;
            margin:0px -6px -8px -6px;
            -moz-border-radius:0px 0px 6px 6px;
            -webkit-border-radius:0px 0px 6px 6px;
            border-radius:0px 0px 6px 6px;
            }
    .pdf_count span{color:#666;}
            </style>';
}
function pdf_file_url(){
    global $wp_query;
    $custom = get_post_custom($wp_query->post->ID);
    echo $custom['link'][0];
}

And to display the link in the theme:

<? pdf_file_url(); ?>

I changed the post type from 'post' to 'events' and the meta box appears in the 'events' page.
So far so good.
It does save the pdf the first time around. And also it displays the correct link.
But then if I try to change the pdf it doesn't save it. It displays the first one again.

I am trying to attach a pdf file to a custom post type.
I have found this snippet at wpsnipp.
The code does the trick, but only for posts.
I have a custom post type named 'events' and I can't make it work.

add_action("admin_init", "pdf_init");
add_action('save_post', 'save_pdf_link');
function pdf_init(){
    add_meta_box("my-pdf", "PDF Document", "pdf_link", "post", "normal", "low");
    }
function pdf_link(){
    global $post;
    $custom  = get_post_custom($post->ID);
    $link    = $custom["link"][0];
    $count   = 0;
    echo '<div class="link_header">';
    $query_pdf_args = array(
            'post_type' => 'attachment',
            'post_mime_type' =>'application/pdf',
            'post_status' => 'inherit',
            'posts_per_page' => -1,
            );
    $query_pdf = new WP_Query( $query_pdf_args );
    $pdf = array();
    echo '<select name="link">';
    echo '<option class="pdf_select">SELECT pdf FILE</option>';
    foreach ( $query_pdf->posts as $file) {
       if($link == $pdf[]= $file->guid){
          echo '<option value="'.$pdf[]= $file->guid.'" selected="true">'.$pdf[]= $file->guid.'</option>';
             }else{
          echo '<option value="'.$pdf[]= $file->guid.'">'.$pdf[]= $file->guid.'</option>';
             }
            $count++;
    }
    echo '</select><br /></div>';
    echo '<p>Selecting a pdf file from the above list to attach to this post.</p>';
    echo '<div class="pdf_count"><span>Files:</span> <b>'.$count.'</b></div>';
}
function save_pdf_link(){
    global $post;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){ return $post->ID; }
    update_post_meta($post->ID, "link", $_POST["link"]);
}
add_action( 'admin_head', 'pdf_css' );
function pdf_css() {
    echo '<style type="text/css">
    .pdf_select{
            font-weight:bold;
            background:#e5e5e5;
            }
    .pdf_count{
            font-size:9px;
            color:#0066ff;
            text-transform:uppercase;
            background:#f3f3f3;
            border-top:solid 1px #e5e5e5;
            padding:6px 6px 6px 12px;
            margin:0px -6px -8px -6px;
            -moz-border-radius:0px 0px 6px 6px;
            -webkit-border-radius:0px 0px 6px 6px;
            border-radius:0px 0px 6px 6px;
            }
    .pdf_count span{color:#666;}
            </style>';
}
function pdf_file_url(){
    global $wp_query;
    $custom = get_post_custom($wp_query->post->ID);
    echo $custom['link'][0];
}

And to display the link in the theme:

<? pdf_file_url(); ?>

I changed the post type from 'post' to 'events' and the meta box appears in the 'events' page.
So far so good.
It does save the pdf the first time around. And also it displays the correct link.
But then if I try to change the pdf it doesn't save it. It displays the first one again.

Share Improve this question asked Jun 21, 2013 at 7:04 belacqua16belacqua16 311 gold badge1 silver badge2 bronze badges 2
  • What is use of $pdf array? If not required remove it and see if it works. – Rajeev Vyas Commented Jun 21, 2013 at 7:38
  • Thank you. Apparently it was of no use. Commented it out, nothing changed. Still the same problem though. – belacqua16 Commented Jun 21, 2013 at 8:00
Add a comment  | 

3 Answers 3

Reset to default 11

Here this is my code which i used in my wordpress site in custom post type for adding the pdf to the post and its work for me try to change its and use it. Hope it will help

function add_custom_meta_boxes() {  
    add_meta_box('wp_custom_attachment', 'Hotel Brochure', 'wp_custom_attachment', 'hotel_post', 'normal', 'high');  
}
add_action('add_meta_boxes', 'add_custom_meta_boxes');  

function wp_custom_attachment() {  
    wp_nonce_field(plugin_basename(__FILE__), 'wp_custom_attachment_nonce');
    $html = '<p class="description">';
    $html .= 'Upload your PDF here.';
    $html .= '</p>';
    $html .= '<input type="file" id="wp_custom_attachment" name="wp_custom_attachment" value="" size="25">';
    echo $html;
}

add_action('save_post', 'save_custom_meta_data');
function save_custom_meta_data($id) {
    if(!empty($_FILES['wp_custom_attachment']['name'])) {
        $supported_types = array('application/pdf');
        $arr_file_type = wp_check_filetype(basename($_FILES['wp_custom_attachment']['name']));
        $uploaded_type = $arr_file_type['type'];

        if(in_array($uploaded_type, $supported_types)) {
            $upload = wp_upload_bits($_FILES['wp_custom_attachment']['name'], null, file_get_contents($_FILES['wp_custom_attachment']['tmp_name']));
            if(isset($upload['error']) && $upload['error'] != 0) {
                wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
            } else {
                update_post_meta($id, 'wp_custom_attachment', $upload);
            }
        }
        else {
            wp_die("The file type that you've uploaded is not a PDF.");
        }
    }
}

function update_edit_form() {
    echo ' enctype="multipart/form-data"';
}
add_action('post_edit_form_tag', 'update_edit_form');

To get the PDF

$hotel_brochure = get_post_meta( $post_id, 'wp_custom_attachment', true );
$hotel_brochure['url']

I just got this working last night using the above code (and the extra comment) and there are a few things I'd like to add here. First, in the "To get the PDF" section, 'wpcf-brochure' should be changed to 'wp_custom_attachment'. Next, to answer the final question from OP, to make it appear in the back end, here's the technique I used. Before the line that says "echo $html;" in functions.php, add:

$filearray = get_post_meta( get_the_ID(), 'wp_custom_attachment', true );
$this_file = $filearray['url'];
if($this_file != ""){
   $html .= '<div>Current file:<br>"' . $this_file . '"</div>';
}

Here is a little boost for the one who wants to fix and fix the accepted answer:

define('PREFIX', 'a-good-prefix-');
echo '<input type="file" name="' . PREFIX . 'attachment">';
add_action('save_post', function ($post_id) {
  $key = PREFIX . 'attachment';
  if (empty($_FILES[$key]['name'])) return;
  if (metadata_exists('post', $post_id, $key)) {
    unlink(get_post_meta($post_id, $key, true)['file']);
  }
  $name = $_FILES[$key]['name'];
  $tmp = $_FILES[$key]['tmp_name'];
  $bits = file_get_contents($tmp);
  $upload = wp_upload_bits($name, null, $bits);
  if (isset($upload['error']) && $upload['error'] !== false) {
    wp_die('Upload error: ' . $upload['error']);
  } else {
    update_post_meta($post_id, $key, $upload);
  }
});

Actual sources: https://code.tutsplus/articles/attaching-files-to-your-posts-using-wordpress-custom-meta-boxes-part-1--wp-22291.

发布评论

评论列表(0)

  1. 暂无评论