How can I put these codes into function.php in WordPress? - wordpress

I want to upload file with Chinese character to a WordPress website. However, the name of the file is gibberish. I have searched the question and found some solutions. One is to modify the //wp-admin/includes/file.php
function wp_handle_upload( &$file, $overrides = false, $time = null ) {
//….
// Move the file to the uploads dir
//$new_file = $uploads['path'] . “/$filename”;
$new_file = $uploads['path'] . “/” . iconv(“UTF-8″,”GB2312″,$filename);
//…
//return apply_filters( ‘wp_handle_upload’, array( ‘file’ => $new_file, ‘url’ => $url, ‘type’ => $type ), ‘upload’ );
return apply_filters( ‘wp_handle_upload’, array( ‘file’ => $uploads['path'] . “/$filename”, ‘url’ => $url, ‘type’ => $type ) , ‘upload’);
}
As I know, it changes the encoding of the filename. But I want to put it in the function.php in the theme folder. What can I do ?

Related

Upload file to custom folder wordpress

I have searched extensively unsuccessfully for an answer to this one.
I want to upload files from Contact Form 7 to a folder in the root.
I can upload the files to the upload folder but that is not satisfactory.
I found code which would change the folder location, but cannot see how to load the attachment to this file.
$folderPath = "/candidates//candidate_id/photos/";
mkdir(ABSPATH.$folderPath, 0777, true);
$filename = $image_name;
if ($filename > '') {
require(ABSPATH . 'wp-admin/includes/admin.php');
$wp_filetype = wp_check_filetype(basename($filename), null);
$attachment = array(
'guid' => $wp_upload_dir['url'] . '' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filename, $newpostid);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
wp_update_attachment_metadata($attach_id, $attach_data);
//Define the new Thumbnail can be also a ACF field
update_post_meta($newpostid, "_thumbnail_id", $attach_id);
}
The new directory appears but the images still end up in the uploads folder.
I cannot see where to define the new folder path in the if ($filename condition.
I can now upload to the custom folder but the file permission of image is 0400.
How can we change that?
Code as follows:
'$folderPath = "/candidates//candidate_id/photos/";
mkdir(ABSPATH.$folderPath, 0777, true);
$filename = $image_name;
if ($filename > '') {
require(ABSPATH . 'wp-admin/includes/admin.php');
$wp_filetype = wp_check_filetype(basename($filename), null);
$attachment = array(
'guid' => $wp_upload_dir['url'] . '' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filename, $newpostid);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
wp_update_attachment_metadata($attach_id, $attach_data);
//Define the new Thumbnail can be also a ACF field
update_post_meta($newpostid, "_thumbnail_id", $attach_id);
}
The new directory appears but the images still end up in the uploads folder.
I cannot see where to define the new folder path in the if ($filename condition.
I have tried the following which uploads to new directory but photo has permission 0400. How can I change to 0644?
`
$folderPath = "/candidates/".$time."/photos/";
mkdir(ABSPATH.$folderPath, 0755, true);
$destination= ABSPATH.$folderPath;
// save any attachments to a temp directory
if(strlen($image_name) > 0 and !ctype_space($image_name)) {
$mail_attachments = explode(" ", $image_name);
foreach($mail_attachments as $attachment) {
$uploaded_file_path = ABSPATH . 'wp-content/uploads/wpcf7_uploads/' . $attachment;
$new_filepath = $destination .'/'. $attachment;
rename($image_location, $new_filepath);
}
}`
Here is what I came up with,
function contactform7_before_send_mail( $form_to_DB ) {
global $wpdb;
$form_to_DB = WPCF7_Submission::get_instance();
if ( $form_to_DB )
$formData = $form_to_DB->get_posted_data();
$uploaded_files = $form_to_DB->uploaded_files(); // this allows you access to the upload file in the temp location
$time = /*date("dmY")."".*/time() ;
if (!empty($formData[Photo])){
$image_name = $formData[Photo];
//$image_name = $time.".jpg";
} else {$image_name="";}
$image_location = $uploaded_files[Photo];
if (!empty($formData[Photo])){
$folderPath = "/candidates/".$time."/photos/";
} else {$folderPath= "/empty/index.php/";}
mkdir(ABSPATH.$folderPath, 0755,true);
$destination= ABSPATH.$folderPath;
// save any attachments to a temp directory
$new_filepath = $destination .'/'. $image_name;
rename($image_location, $new_filepath);
chmod($new_filepath, 0644);

Image upload by image URL or image Link in WordPress

How to upload a image by image URL or link of the image in WordPress media library by programming.
You can do that by passing the $_REQUEST['image'] via URL , by doing the following.
// $filename should be the path to a file in the upload directory.
$filename = $_REQUEST['image'];
// The ID of the post this attachment is for.
$parent_post_id = 37;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// 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' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
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, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $parent_post_id, $attach_id );
Just skip the part you don't need , like set the image to post -> set_post_thumbnail() , I have added it for better reference to attach the image to post.

upload image with wordpress rest api

I am having trouble uploading an image with the WordPress REST API (WP-API). Can someone provide some sample code. Basically I have an image that I got from a service and I'm showing in an <img> tag. Now I need to take that image and save it in the media library using javascript.
Alternatively (not using WP-API) if there is a plugin that would do that, I can pass the url for the image to get is saved in the media library.
Thanks
You can use the wp_insert_attachment if API is not preferred. Source
Ignore the $parent_post_id if the media library is not post specific.
You can retrieve the image url using this trick: Retrieve images and then use the variable for $filename
// $filename should be the path to a file in the upload directory.
$filename = '/path/to/uploads/2013/03/filename.jpg';
// The ID of the post this attachment is for.
$parent_post_id = 37;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// 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' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
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, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

Get attachment ID by file path in WordPress

I know the path of the file and I like to get the attachment ID.
There's a function wp_get_attachment_url() which requires the ID to get the URL but I need it reverse (with path not URL though)
UPDATE: since wp 4.0.0 there's a new function that could do the job. I didn't tested it yet, but it's this:
https://developer.wordpress.org/reference/functions/attachment_url_to_postid/
OLD ANSWER: so far, the best solution I've found out there, is the following:
https://frankiejarrett.com/2013/05/get-an-attachment-id-by-url-in-wordpress/
I think It's the best for 2 reasons:
It does some integrity checks
[important!] it's domain-agnostic. This makes for safe site moving. To me, this is a key feature.
I used this cool snipped by pippinsplugins.com
Add this function in your functions.php file
// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
Then use this code in your page or template to store / print / use the ID:
// set the image url
$image_url = 'http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg';
// store the image ID in a var
$image_id = pippin_get_image_id($image_url);
// print the id
echo $image_id;
Original post here: https://pippinsplugins.com/retrieve-attachment-id-from-image-url/
Hope ti helps ;)
Francesco
Try attachment_url_to_postid function.
$rm_image_id = attachment_url_to_postid( 'http://example.com/wp-content/uploads/2016/05/castle-old.jpg' );
echo $rm_image_id;
More details
None of the other answers here appear to work properly or reliably for a file path. The answer using Pippin's function also is flawed, and doesn't really do things "the WordPress Way".
This function will support either a path OR a url, and relies on the built-in WordPress function attachment_url_to_postid to do the final processing properly:
/**
* Find the post ID for a file PATH or URL
*
* #param string $path
*
* #return int
*/
function find_post_id_from_path( $path ) {
// detect if is a media resize, and strip resize portion of file name
if ( preg_match( '/(-\d{1,4}x\d{1,4})\.(jpg|jpeg|png|gif)$/i', $path, $matches ) ) {
$path = str_ireplace( $matches[1], '', $path );
}
// process and include the year / month folders so WP function below finds properly
if ( preg_match( '/uploads\/(\d{1,4}\/)?(\d{1,2}\/)?(.+)$/i', $path, $matches ) ) {
unset( $matches[0] );
$path = implode( '', $matches );
}
// at this point, $path contains the year/month/file name (without resize info)
// call WP native function to find post ID properly
return attachment_url_to_postid( $path );
}
Cropped URLs
None of the previous answers supported ID lookup on attachment URLs that contain a crop.
e.g: /uploads/2018/02/my-image-300x250.jpg v.s. /uploads/2018/02/my-image.jpg
Solution
Micah at WP Scholar wrote a blog post and uploaded the code to this Gist. It handles both original and cropped URL lookup.
I included the code below as a reference but, if you find useful, I'd encourage you to leave a comment on his post or star the gist.
/**
* Get an attachment ID given a URL.
*
* #param string $url
*
* #return int Attachment ID on success, 0 on failure
*/
function get_attachment_id( $url ) {
$attachment_id = 0;
$dir = wp_upload_dir();
if ( false !== strpos( $url, $dir['baseurl'] . '/' ) ) { // Is URL in uploads directory?
$file = basename( $url );
$query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'meta_query' => array(
array(
'value' => $file,
'compare' => 'LIKE',
'key' => '_wp_attachment_metadata',
),
)
);
$query = new WP_Query( $query_args );
if ( $query->have_posts() ) {
foreach ( $query->posts as $post_id ) {
$meta = wp_get_attachment_metadata( $post_id );
$original_file = basename( $meta['file'] );
$cropped_image_files = wp_list_pluck( $meta['sizes'], 'file' );
if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) {
$attachment_id = $post_id;
break;
}
}
}
}
return $attachment_id;
}
Another pro with this solution is that we leverage the WP_Query class instead of making a direct SQL query to DB.
Find IDs for resized images, PDFs and more
Like GFargo pointed out, most of the answers assume the attachment is an image. Also attachment_url_to_postid assumes a url (not a file path).
I believe this better answers the actual question when supplied a file (with path):
function getAttachmentIDFromFile($filepath)
{
$file = basename($filepath);
$query_args = array(
'post_status' => 'any',
'post_type' => 'attachment',
'fields' => 'ids',
'meta_query' => array(
array(
'value' => $file,
'compare' => 'LIKE',
),
)
);
$query = new WP_Query($query_args);
if ($query->have_posts()) {
return $query->posts[0]; //assume the first is correct; or process further if you need
}
return 0;
}
Based on the answer from #FrancescoCarlucci I could do some improvements.
Sometimes, for example when you edit an image in WordPress, it creates a copy from the original and adds the copys upload path as post meta (key _wp_attached_file) which is not respected by the answer.
Here the refined query that includes these edits:
function jfw_get_image_id($file_url) {
$file_path = ltrim(str_replace(wp_upload_dir()['baseurl'], '', $file_url), '/');
global $wpdb;
$statement = $wpdb->prepare("SELECT `ID` FROM `wp_posts` AS posts JOIN `wp_postmeta` AS meta on meta.`post_id`=posts.`ID` WHERE posts.`guid`='%s' OR (meta.`meta_key`='_wp_attached_file' AND meta.`meta_value` LIKE '%%%s');",
$file_url,
$file_path);
$attachment = $wpdb->get_col($statement);
if (count($attachment) < 1) {
return false;
}
return $attachment[0];
}

Wrong URL when using wp_insert_attachment

I created a plugin as 3rd party to acomodate system with wordpress website on main site. So the scenario is:
when user hit submit on the system it will also added to wordpress website, it's working perfect, no problem at all. but when i try to set the featured image through wp_insert_attachment it keep me give a URL like
http://xxxxx.com/wp-content/uploads/http://xxxxx.com/system/media/.../xx.jpg
what i want to be is only http://xxxxx.com/system/media/.../xx.jpg saved as featured image, is it possible to do so?
here is my current script
if($pt == "pictures"){
$filename_url = $_GET["dml_file"];
$mime = wp_check_filetype($filename_url, null);
$data = array(
'post_mime_type' => $mime['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($_GET["dml_file"])),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment($data, $filename_url, $pid);
update_post_meta($pid, $custom_field, $attachment_id);
}else{
update_post_meta($pid, $custom_field, $_GET["dml_file"]);
}
I have tried to use file_get_contents and file_put_contents to create image in WP installation, but I don't want that way.
The system is submitting this:
http://user:pass!#localhost/wp-content/plugins/dml3rdparty/dmlsubmit.php?dml_sa‌ve=save&dml_file=http://xxx.xxx.xxx.xxx/dml/assets/media/Accreditation/download.d‌15bdf4e9e.jpg&dml_type=Print Quality Photos&dml_description=test|download.jpg&dml_status=publish
From wp_insert_attachment documentation (my emphasis in bold):
$filename
(string) (optional) Location of the file on the server. Use absolute path and not the URI of the file. The file MUST be on the uploads directory. See wp_upload_dir()
Default: false
Much probably, you can solve this with media_handle_sideload().
This function gets the file content using cURL:
function my_file_get_contents($url){
$options = array(
CURLOPT_AUTOREFERER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10
);
$ch = curl_init($url);
curl_setopt_array($ch,$options);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
This function uses the above to get the image, saves it to the uploads folder, and sets it as a featured image for a post:
function my_featured_image($image_url,$post_id){
$upload_dir = wp_upload_dir();
$image_data = my_file_get_contents($image_url);
$filename = strtok($image_url, '?');
$filename = basename($filename);
if(wp_mkdir_p($upload_dir["path"])){
$file = $upload_dir["path"]."/".$filename;
}else{
$file = $upload_dir["basedir"]."/".$filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename,null);
$post_author = get_post_field("post_author",$post_id);
$attachment = array(
"post_author" => $post_author,
"post_mime_type" => $wp_filetype["type"],
"post_title" => sanitize_file_name($filename),
"post_content" => "",
"post_status" => "inherit"
);
$attach_id = wp_insert_attachment($attachment,$file,$post_id);
require_once(ABSPATH."wp-admin/includes/image.php");
$attach_data = wp_generate_attachment_metadata($attach_id,$file);
$res1 = wp_update_attachment_metadata($attach_id,$attach_data);
$res2 = set_post_thumbnail($post_id, $attach_id);
}
Call with:
my_featured_image($image_url,$post_id);

Resources