i am trying to insert posts automatically to wordpress. Posts i posted is very well but somehow i can't generate metadatas for thumbnails.
Here is my code for metadatas
$filetype = wp_check_filetype( basename( $thumb ), null );
$bol = explode('/', $thumb);
$fileur = $bol[count($bol)-1];
$wp_upload_dir = wp_upload_dir();
$tits = $wp_upload_dir['path'].'/'.basename($thumb);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $thumb ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $thumb ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id=wp_insert_attachment($attachment, $tits, $post_id);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $tits );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail($post_id,$attachment_id);
I read all the connected questions on community but it doesnt helped my issue. Best regards
According to this WP wiki page: wp_insert_attachment you must use unchanged file path from upload dir for these functions: wp_insert_attachment, wp_generate_attachment_metadata
In your codebase, I see that you're doing something wrong with your $thumb like extracting its basename and building a new path that lives in $tits. I am 99% sure that the problem is of wrong file path.
Related
I have a custom php form that upload images to a folder on my website. Currently that folder is outside the wp-content folder.
I want the content of the folder to be automatically uploaded to Google drive. There are plenty of plugins or a zapier solution to do that if the folder is in the wp media folder.
My question is...Can I just upload the images directly to the wp media folder or do I need to use a special wp method/function/api call.
Yes you can upload media directly to the media library. Given your situation media_handle_upload() is probably the most logical way. Can read its documentation here: https://developer.wordpress.org/reference/functions/media_handle_upload/
Take a look at this https://wordpress.stackexchange.com/a/60807/180725
Once you upload the media (to where you want, ftp, dropbox, s3 etc) you will need to register it with Wordpress.
$file_name = 'Some Name';
$file_path = '/path/to/uploads/2012/08/04/newfile.jpg';
$file_url = 'http://url/to/uploads/2012/08/04/newfile.jpg';
$wp_filetype = wp_check_filetype($file, null);
$attachment = array(
'guid' => $file_url,
'post_mime_type' => $wp_filetype['type'],
'post_title' => $file_name,
'post_status' => 'inherit',
'post_date' => date('Y-m-d H:i:s')
);
$attachment_id = wp_insert_attachment($attachment, $file_path);
$attachment_data = wp_generate_attachment_metadata($attachment_id, $file_path);
wp_update_attachment_metadata($attachment_id, $attachment_data);
If you are looking for a solution to upload files to wordpress Mediathek / Library from an external Source/URL, I recommend the following code:
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
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 );
$attachment = array(
'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 );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_ID, $attach_id );
Original post here: https://wordpress.stackexchange.com/a/169598
In this piece of code, an empty file is getting stored in upload folder, but not a proper image file attached. I don't know why.
I'm also not getting the proper usage of wp_upload_bits, it writes a file in upload folder. I don't know how to change that to suite it for the uploading of an image.
I'm totally confused with the error in my code.
I know that there are multiple duplicate question related to it in stack overflow, but I'm not getting a proper result while using the solution described there. Please help me to find a solution.
My piece of code is as follows:
$upload = wp_upload_bits( $_FILES['file']['name'], null, file_get_contents( $_FILES['file']['tmp_name'] ) );
$wp_filetype = wp_check_filetype( basename( $upload['file'] ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $upload['url'] ,
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename( $upload['file'] )),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
update_post_meta( $post_id, '_thumbnail_id', $attach_id );
set_post_thumbnail( $post_id, $attach_id );
While using this code,attach file is getting stored in WordPress DB, but not in upload folder (media library).
I'm new to WordPress, so I am unable to find a solution for the reason of not storing a proper attached image file in upload folder.
I'm developing a site in which a user is able to capture his/her pic(via .getusermedia) which updated as the post thumbnail.
The problem is that the post thumbnail gets updated for all users - I want the post thumbnail to be updated only for that particular user
function Generate_Featured_Image( $filename, $parent_post_id ){
require('/wp-load.php');
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$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'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
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 );
//add_user_meta( $current_user_id, $parent_post_id, $attach_id);
set_post_thumbnail( $parent_post_id, $attach_id );
}
script.php
Generate_Featured_Image( $addroot.$current_user_id.$extimage, 88 );
// addroot=path ext-extension(.jpg) (this is name of file saved)
i tried to user add_user_meta to accomplish the task but couldn't even get a start
UPDATE
<?php
// $filename is succesfully saved as currentuserid+.jpg.
$addroot = '/wp-content/uploads/2016/09/';
$current_user_id = get_current_user_id();
$extimage = '.jpg';
$filename = $addroot.$current_user_id.$extimage;
$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, 0 );
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 );
update_user_meta( get_the_ID(), $filename , $_POST[ $filename ] );
?>
how to proceed further by calling the image to by $attach_id from usermeta and displayinf it to user as thumbnail- unable to figure this step
You can't really set a different featured image for post based on a user. There is just one post, therefore only one featured image for it.
If you want to display a different image, based on which user is viewing the post, save that use wp_insert_attachment( $attachment, $filename, 0) to insert attachment without binding it to the post. Then save that $attach_id to the usermeta table. Then, when user is viewing that post, simply get $attach_id with get_user_meta and display that image (you can use wp_get_attachment_url for example) instead of featured image of the post.
UPDATE
First, saving user meta should look like this
update_user_meta($current_user_id, '_avatar_id', $attach_id);
Second, in the beginning, you should check if user is logged in with is_user_logged_in function.
Third, you should check for user had avatar before and remove it (I mean, why store their old one after they have a new one, right?) like so:
$old_attach=get_user_meta($current_user_id, '_avatar_id', true);
if(is_numeric($old_attach))
{
wp_delete_attachment($old_attach, true);
}
Your final code to save avatar should look like:
if (is_user_logged_in())
{
$addroot = '/wp-content/uploads/2016/09/';
$current_user_id = get_current_user_id();
$extimage = '.jpg';
$filename = $addroot . $current_user_id . $extimage;
$filetype = wp_check_filetype(basename($filename), null);
$wp_upload_dir = wp_upload_dir();
$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'
);
$attach_id = wp_insert_attachment($attachment, $filename, 0);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $filename));
$old_attach = get_user_meta($current_user_id, '_avatar_id', true);
if (is_numeric($old_attach))
{
wp_delete_attachment($old_attach, true);
}
update_user_meta($current_user_id, '_avatar_id', $attach_id);
}
else
{
//show error here or something
}
Now, to access it, you can write a simple function, like this:
function get_user_avatar()
{
if (is_user_logged_in())
{
$avatar_id = get_user_meta(get_current_user_id(), '_avatar_id', true);
if (is_numeric($avatar_id))
{
return'<img src="' . wp_get_attachment_url($avatar_id) . '" alt="User avatar"/>';
}
else
{
return '<img src="url_to_your_default_avatar" alt="User avatar"/>';
}
}
return false;
}
I want to upload an image to wordpress via a php script completely outside wordpress. I know what tables i have to insert data to. However I've noticed that if i pass through the normal way wordpress creates various sizes of the image and also save this in db. Is there a way to simulate the upload of the image using a script completely outside wordpress.
Yes, it would be something like this:
<?php
header('Response: HTTP/1.1 200 OK');
define('WP_USE_THEMES', false);
require('../../../../wp-load.php');
$uploadedfile = $_FILES['image'];
if($uploadedfile['size'] > 0){
$upload_overrides = array( 'test_form' => false );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ($movefile) {
$wp_filetype = $movefile['type'];
$filename = $movefile['file'];
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename);
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 );
die(json_encode(array('type'=>'error', 'text' => 'Ok', 'error' => 0)));
}else{
die(json_encode(array('type'=>'error', 'error' => 1)));
}
}
die(json_encode(array('type'=>'error', 'error' => 2)));
}
?>
Please note that i´ve pasted my code, you´ll have to work with it a little bit ;)
Here is the function that I used to insert attachments to a post.
function insert_entries($filename, $parent_post_id){
$wp_upload_dir = wp_upload_dir();
$filetype = wp_check_filetype( basename( $filename ), null );
$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'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
The issue with this is that, When I am trying to insert any files after inserting a 3gp or m4v file, its not getting inserted. Any insight to solve this is welcome..
Thanks in advance..
Atlast got it fixed.
The reason for the issue was when we try to insert any audio or video files the wordpress tries extract its metadata which was causing for a fatal error.
The simple fix for this is to go to includes/image.php and remove all references to wp_read_video_metadata()