在WordPress循环中使用自定义元框日期

时间:2018-08-29 14:53:34

标签: php wordpress

我正在使用functions.php文件中的以下脚本将PDF上载到自定义帖子类型,但是我不确定如何在WordPress循环中检索PDF URL:

function add_custom_meta_boxes() {  
    add_meta_box('wp_custom_attachment', 'PDF Newsletter', 'wp_custom_attachment', 'newsletter', '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">';
    $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>';
    }
    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 {
                add_post_meta($id, 'wp_custom_attachment', $upload);
                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');

这是我正在使用的循环,包括我添加PDF网址失败的尝试:

                <?php
                $args = array( 'post_type' => 'newsletter', 'posts_per_page' => 10 );
                $loop = new WP_Query( $args );
                while ( $loop->have_posts() ) : $loop->the_post();
                  the_title();
                  echo '<div class="entry-content">';
                  the_content(); ?>
                   <?php 
                    $news_pdf = get_post_meta( $post_id, 'wp_custom_attachment', true );
                    $news_pdf['url']
                  ?>
                 <?php echo '</div>';
                endwhile;
                ?>

1 个答案:

答案 0 :(得分:1)

请先在循环中将 $ post_id 更改为 get_the_ID()

$ news_pdf ['url'] 更改为:

 echo $news_pdf['url'];

谢谢