以编程方式添加附件(pdf,word,excel或ppt文件)

时间:2015-09-02 06:09:42

标签: php wordpress attachment

以编程方式我扫描目录中的文件(完成),在我将每个文件作为帖子(完成)插入后,同时每个帖子必须作为附件插入并保存在wordpress中上传文件夹。

我需要插入附件详细信息并保存相应的文件,我仍然坚持使用该部分,这是我编写的代码

<?php
$current_user = wp_get_current_user();
$userRoleArray = $current_user->roles;
$current_userid = $current_user->ID;

$directory = 'D:\BD Repository'; //Base Directory
$project = "bdqueries";

/*** Scan the Directory ***/
function listfolders($dir) { 
    static $alldirs = array();
    $dirs = glob($dir . '/*', GLOB_ONLYDIR);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = basename($d);
    }
    foreach ($dirs as $dir) listfolders($dir);
    return $alldirs;
}

$folder_list = listfolders($directory); // Function to get all the folders and subfolders

foreach($folder_list as $folder_name){  // Saving Folders as Tags in wp_bdqueries_tags table
    $folder_slug = strtolower(preg_replace('/\s+/', '-', $folder_name));

    global $wpdb;
    $wpdb->insert("wp_bdqueries_tags", array(
        "tag_group_id"      => 44,
        "tag_name"          => $folder_name,
        "tag_slug"          => $folder_slug,
        "tag_status"        => 'approved',
        "tag_description"   => '',
        "tag_postedby"      => 0,
        "tag_moderatedby"   => 0,
        "tag_addedon"       => date('Y-m-d h:i:s')
    ));
    echo $folder_name.'***'.$folder_slug.'<br>';
}

/*** Get All the Files | Insert the posts and attachments | Copy files  ***/

$allfiles = array();

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

while($it->valid()) {
    if (!$it->isDot()) {
        $SubPath = $it->getSubPath();
        $path = $it->key();
        $filetype = wp_check_filetype(basename($path),null); // Check the type of file for'post_mime_type'

        $filename = preg_replace("/\.[^.]+$/", "", basename($path));    
        $file_slug = strtolower(preg_replace('/\s+/', '-', $filename));
        echo '<br>Filename: <a href="'.$path.'" alt="Download" target="_blank" title="Download" >'. $filename . "</a><br>";                             

        $allfiles[] = $filename; //saving all file names in array

    /*Inserting each file as a post*/
        $file_post = array(
            'post_title'            => $filename,
            'post_status'           => 'publish',
            'post_date'             => date('Y-m-d h:i:s'),
            'post_date_gmt'         => gmdate('Y-m-d h:i:s'),
            'post_author'           => $current_userid,
            'post_name'             => $file_slug,
            'post_type'             => 'bdlibrary',
            'guid'                  => ''
        );

        // Insert the post into the database
        //wp_insert_post($file_post);
        $post_id = wp_insert_post($file_post, $wp_error);
    /*** END *** Inserting each file as a post*/

    /*Inserting each attachment details*/
        $wp_upload_dir = wp_upload_dir(); // Get the path to the upload directory.
        $target_dir = UPLOADS."/bd_library_uploads/";
        $target = $wp_upload_dir['basedir'].'/bd_library_uploads';
        // Prepare an array of post data for the attachment.
        $attachment = array(
            'guid'                  => $wp_upload_dir['url'] . '/' . basename($path), 
            'post_mime_type'        => $filetype['type'],
            'post_title'            => preg_replace( '/\.[^.]+$/', '', basename($path)),
            'post_content'          => '',
            'post_name'             => $file_slug,
            'post_status'           => 'inherit',
            'post_date'             => date('Y-m-d h:i:s'),
            'post_date_gmt'         => gmdate('Y-m-d h:i:s'),
            'post_type'             => 'attachment',
        );

        // Insert the attachment.
        $attach_id = wp_insert_attachment($attachment, $target, $post_id);

    /*** END *** Inserting each attachment details*/

        $tags = explode("\\", $SubPath);
        echo "Tags: ";

    /*** Use post_id and Insert into wp_tags_association table ***/
        foreach ($tags as $tag) { 
            if($tag !== end($tags)){
                echo $tag.' | ';
            }
            else{
                echo $tag."<br>";
            }

            $tagSlug = strtolower(preg_replace('/\s+/', '-', $tag));
            echo $tagSlug;
            global $wpdb;
            $taginfo = $wpdb->get_row("SELECT tag_id,tag_group_id FROM wp_bdqueries_tags WHERE tag_slug = '".$tagSlug."'", ARRAY_A);
            $tag_id = $taginfo['tag_id'];
            $tag_group_id = $taginfo['tag_group_id'];
            if($tag_id){                    
                $tassc_project = $project;
                $tassc_userid = $current_userid;
                $tassc_tagged_under = 'bdlibrary';
                $tassc_tag_assc_itemid = $post_id;
                //echo "apan idhar hai";

                $wpdb->insert("wp_tags_association", array(
                    "tassc_tagid"           => $tag_id,
                    "tassc_tag_groupid"     => $tag_group_id,
                    "tassc_project"         => $tassc_project,
                    "tassc_userid"          => $tassc_userid,
                    "tassc_tagged_under"    => $tassc_tagged_under,
                    "tassc_tag_assc_itemid" => $tassc_tag_assc_itemid,
                    "tag_added_date"        => date('Y-m-d h:i:s')
                ));
            }
        }
    }
    $it->next();
}

1 个答案:

答案 0 :(得分:2)

我必须构建类似的解决方案,这就是我实现结果的方式。我希望此代码段有助于解决您的问题:

    /* $post_id is the id of the post which you want to associate the attachement. you don't need this if you don't want to associate attachment with any post */
/*read source file and upload it to destination folder*/
$upload_dir = wp_upload_dir();
$image_remote_path = $original_directory.'/'.$image;
$image_local_path = $upload_dir['path'].'/'.$image;
$image_local_url = $upload_dir['url'].'/'.basename( $image_local_path );
$remotehandle = fopen($image_remote_path, 'rb');
$localhandle = fopen($image_local_path, 'w');
while( $chunk = fread($remotehandle, 8192)) {
    fwrite($localhandle, $chunk);
}
fclose($remotehandle);
fclose($localhandle);
/* end of uploading from source to destination */
$filetype = wp_check_filetype( basename( $image_local_path ), null );
// Prepare an array of post data for the attachment.
$attachment = array(
    'guid'           => $image_local_url, 
    'post_mime_type' => $filetype['type'],
    'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $image_local_path ) ),
    'post_content'   => $image_caption_data[$i],
    'post_status'    => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $image_local_path, $post_id ); /*do not put post id if you don't want to associate with any post*/
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $image_local_path );
wp_update_attachment_metadata( $attach_id, $attach_data );