php 将文件移动到uploads director,在MG中插入Attachment,为Post设置特色图像

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 将文件移动到uploads director,在MG中插入Attachment,为Post设置特色图像相关的知识,希望对你有一定的参考价值。

// MOVE FILE INTO THE WP UPLOADS DIRECTORY AND THEN "UPLOAD" INTO
// AS AN ATTACHMENT IN THE MEDIA GALLERY< AND ASSOCIATED IT TO A SPECIFIC POST

//Start image url 
	$startImgUrl =  __DIR__ . $file['tmp_name'];
	//Just the file name (with extension)
	$filename = basename($startImgUrl);

	//To Uploads directory Path/Url 
	$wordpress_upload_dir = wp_upload_dir()['path'];

	//fetch the image to put into Media Gallery
	$contents = file_get_contents($startImgUrl);

	// Testing success
	if(file_put_contents($wordpress_upload_dir . "/" . $filename, $contents)) {

        // UPLOAD ATTACHMENT
		// $filename should be the path to a file in the upload directory.
		$filename = $wordpress_upload_dir . "/" . $filename;

		// Check the type of file. We'll use this as the 'post_mime_type'.
		$filetype = wp_check_filetype( basename( $filename ), null );
		$ext = $filetype['ext'];
		$mime = $filetype['type'];

		// Get the path to the upload directory.
		$wp_upload_dir = wp_upload_dir();

		// Prepare an array of post data for the attachment.
		$attachment = array(
			'guid'           => $newFile, //full path
			'post_mime_type' => $mime,
			'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
			'post_content'   => '',
			'post_status'    => 'inherit'
		);

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

        // SET FEATURED IMAGE OF POST

        if(isset($attach_id) && ($attach_id > 0)):
            // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
            if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
                require_once( ABSPATH . 'wp-admin/includes/image.php' );
            }

            // The ID of the post this attachment is for. ()
            $post_id = $_POST["post_id"];
            
            // Generate the metadata for the attachment, and update the database record.
            $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
            wp_update_attachment_metadata( $attach_id, $attach_data );

            set_post_thumbnail( $post_id, $attach_id );
        endif;


	} else {

		//echo "file wasn't moved";
  }

以上是关于php 将文件移动到uploads director,在MG中插入Attachment,为Post设置特色图像的主要内容,如果未能解决你的问题,请参考以下文章

解决PHP move_uploaded_file函数移动图片失败

PHP小知识

Ubuntu Server不会使用PHP“move_uploaded_file”上传文件

PHP在使用move_uploaded_file函数移动文件时一直失败

move_uploaded_file() 无法将文件从 tmp 移动到 dir

如何在 PHP 中将上传的文件移动到另一台主机