Wordpress Updating Attachment Data - wordpress

I'm attempting to add a feature to a plugin that extends media management. This feature would allow you to rename an attachment file. I've been able to complete this with the following code.
public function update_attachment_filename( $post_ID ) {
// Get path to existing file
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Generate new file name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the name and reference to file
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
}
While the original file gets renamed using the above method, all additional image sizes defined in the plugins/theme are not updated. I'm struggling to figure out the best way to accomplish this task.
I've looked into wp_update_attachment_metadata() and wp_generate_attachment_metadata() but am unsure whether they will give me the desired functionality.
Additionally I've looked into something such as:
$file_meta = wp_get_attachment_metadata( $post_ID );
foreach( $file_meta['sizes'] as $image ) {
// Do something
}
Any nudge in the right direction would be greatly appreciated.
Thanks!

I was able to utilize both the wp_generate_attachment_metadata() and the wp_update_attachment_metadata() function to achieve the desired end result.
public function update_attachment_filename( $post_ID ) {
if( isset( $_POST['update_filename'] ) && ! empty( $_POST['update_filename'] ) ) {
// Get path to existing attachment
$file = get_attached_file( $post_ID );
$path = pathinfo( $file );
// Create new attachment name
$file_updated = $path['dirname'] . '/' . $_POST['update_filename'] . '.' . $path['extension'];
// Update the attachment name
rename( $file, $file_updated );
update_attached_file( $post_ID, $file_updated );
// Update attachment meta data
$file_updated_meta = wp_generate_attachment_metadata( $post_ID, $file_updated );
wp_update_attachment_metadata( $post_ID, $file_updated_meta );
}
}

Related

Add a suffix to all image URLs (File URL)

I am trying to add a suffix having certain values (such as min123) to all image URLs on my WordPress website getallnumber.com. The images are located in "/wp-content/uploads/year/month/". After adding the value the URL should be /wp-content/uploads/year/month/image.min123.png. I tried some pieces of codes including the sanitize code but there is no lock. Please help me out!
function sa_sanitize_special_chars ($filename) {
$f=remove_accents( $filename );
return 'min123-'.$f;
}
Add below code snippet in your active theme's functions.php file -
// wp media name suffix on upload
function modify_wp_handle_upload_prefilter( $file ) {
if( isset( $file['name'] ) ) {
$fileinfo = pathinfo( $file['name'] );
if( $fileinfo && isset( $fileinfo['filename'] ) && isset( $fileinfo['extension'] ) ) {
$suffix = 'min123'; // your suffix goes here
$name = $fileinfo['filename'] . '.' . $suffix . '.' . $fileinfo['extension'];
$file['name'] = $name;
}
}
return $file;
}
add_filter( 'wp_handle_upload_prefilter', 'modify_wp_handle_upload_prefilter', 99 );

Replace space with hyphen for image filename on upload

I'm using the code bellow (I found it here on stack overflow from this post) to auto rename image filename and fill alt and title field based on post title.
The good thing is it's working, it's doing its job but problem is with filename : it's using post title with spaces, comas, etc. as filename, which is really not good. It's perfect for filling the title and alt fields but not for a filename.
So, just for the filename, I would like to add something to replace spaces by hyphen (and if possible remove potentials comas or other punctuation)
I thought that the part add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 ); would to the job, but it's not.
But as I'm really not sure what I'm doing, and as I have poor PHP knowledge, I would be very grateful if you could teach me how to make it work :
function file_renamer( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
if( $post_id = array_key_exists("post_id", $_POST) ? $_POST["post_id"] : null) {
if($post = get_post($post_id)) {
return $post->post_title . $ext;
}
}
$my_image_title = $post;
$file['name'] = $my_image_title . - uniqid() . $ext; // uniqid method
// $file['name'] = md5($name) . $ext; // md5 method
// $file['name'] = base64_encode($name) . $ext; // base64 method
return $filename;
}
add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 );
/* Automatically set the image Title, Alt-Text, Caption & Description upon upload */
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
} else {
$post_id = false;
}
if ($post_id != false) {
$my_image_title = get_the_title($post_id);
} else {
$my_image_title = get_post( $post_ID )->post_title;
}
// Sanitize the title: remove hyphens, underscores & extra spaces:
$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );
// Create an array with the image meta (Title, Caption, Description) to be updated
// Note: comment out the Excerpt/Caption or Content/Description lines if not needed
$my_image_meta = array(
'ID' => $post_ID, // Specify the image (ID) to be updated
'post_title' => $my_image_title, // Set image Title to sanitized title
'post_content' => $my_image_title, // Set image Description (Content) to sanitized title
);
// Set the image Alt-Text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );
}
}
Thanks for your help !
So solution was replacing post_title by post_name in file_renamer function.
Exactly this part : change return $post->post_title . $ext; and replace it with return $post->post_name . $ext;
And it's working. On upload, this function is renaming the file name with hyphens and filling title, alt text and description fields based on Post Title (without hyphens).

Add files programmatically to Order in Woocommerce

I'm using the "woocommerce_order_status_completed" hook to create a file dynamically after the user has paid for the order.
I need to add this file to his downloadable area in that order in this hooks.
Any ideias how to attach a file to a order?
woocommerce_order_status_completed you can add below code...
First store the file you have created in uploads using media_handle_upload
if($_FILES){
//if u don't want to $post_id u gan give 0
$attachment_id = media_handle_upload( 'abe_update_epub', $post_id );
if ( is_wp_error( $attachment_id ) ) {
$errors = $attachment_id->get_error_messages();
foreach( $errors as $error ){
echo $error;
}
echo 'There was an error uploading the image';
} else {
// NEW FILE: Setting the name, getting the url and and Md5 hash number
$file_name = 'Epub Files';
$file_url = wp_get_attachment_url($attachment_id);
$md5_num = md5( $file_url );
// Inserting new file in downloadable files
$files[$md5_num] = array(
'name' => $file_name,
'file' => $file_url
);
// Updating database with the new array
$order = new WC_Order($order_id);
if(!empty($files)){
update_post_meta($order->ID,_files,$files));
}
// Displaying a success notice
echo 'The image was uploaded successfully!';
}
}
Hopes this help u..

When i change file_get_contents to WP_Filesystem it doesn't work

I am working on a wordpress theme. It is almost complete. When i check it in theme-check plugin it give the warning
WARNING: file_get_contents was found in the file sources.php File operations
should use the WP_Filesystem methods instead of direct PHP filesystem calls.
Line 84: $fonts = file_get_contents(dirname(__FILE__) . '/gwf.json');
Then i change file_get_contents to WP_Filesystem but it not getting the value or not working.
Here is the code of line 84:
function vp_get_gwf_family()
{
$fonts = file_get_contents(dirname(__FILE__) . '/gwf.json');
$fonts = json_decode($fonts);
$fonts = array_keys(get_object_vars($fonts));
foreach ($fonts as $font)
{
$result[] = array('value' => $font, 'label' => $font);
}
return $result;
}
I was having problems with wp_filesystem due to security settings on the server and ended up changing:
global $wp_filesystem;
$file = $wp_filesystem->get_contents( get_template_directory() . '/assets/js/icomoon-selection.json' );
to:
ob_start();
include dirname(__FILE__) .'/../assets/js/icomoon-selection.json';
$file = ob_get_contents();
ob_end_clean();
Maybe it solves your warnings (the example use of wp filesystem or the workaround).
I was facing the same problem. I used these function to solve it.
public function icon_generator() {
$file = THEMEOO_THEME_DIR . 'inc/icon/fa-icons.json';
if ( is_readable( $file ) ) {
$icons = WP_Filesystem_Direct::get_contents( $file ); // phpcs:ignore WordPressVIPMinimum.Performance.FetchingRemoteData.FileGetContentsUnknown
if ( ! empty( $icons ) ) {
$icons = json_decode( $icons );
if ( isset( $icons->icons ) && ! empty( $icons->icons ) ) {
foreach ( $icons->icons as $icon ) {
echo '<span class="ti-' . esc_attr( $icon ) . '">';
}
}
}
}
die();
}
I think this will solve your problem. For better understanding you can follow this tutorial
If you can't get $wp_filesystem because you are not in the admin environment (e.g. if you are using REST API from wordpress, which is not an "admin" environment), then you can use php's native file_get_contents to replace $wp_filesystem->get_contents().
The param you need to pass into file_get_content() is the string that's after localhost:8080
e.g. for this local file:
http://localhost:8080/wp-content/uploads/2021/11/imagexyz.jpeg
You can acces it by:
$image_content = file_get_contents('wp-content/uploads/2021/11/imagexyz.jpeg');

How to Fetch the Shortcode Parameters Value in WordPress?

[amazon_s3 bucket=my_bucket_name object=my_file_name.ext]
Hi all i need to know how to fetch the parameter value in the above shortcode. For Example: Object is the attributes then how can i fetch the object value my_file_name.ext. I am using the woocommerce s3 plugin. I am not sure i customized the woocommerce to fetch the file name show in my account page here is the code.
function filename_wc_downloads( $link, $download )
{
$order = new WC_Order( $download['order_id'] );
$download_file_urls = $order->get_downloadable_file_urls(
$download['product_id'],
null,
$download['download_id']
);
foreach( $download_file_urls as $key => $value )
{
if( $value == $download['download_url'] )
{
$url_parts = explode( '/', parse_url( $key, PHP_URL_PATH ) );
$file_name = end( $url_parts );
$link = '<a href="'
. esc_url( $download['download_url'] )
. '">'
. $download['download_name']
. '</a> <small>( '
. $file_name
. ' )</small>';
}
}
return $link;
}
In a Woocommerce all products are uploaded into the media library of upload folder. The above code is to fetch the filename show in my account page if they using direct file path. If i pasted the above shortcode in the product url, that above code doesn't help to fetch the filename. so i need to know from the shortcode how can i get the object value based on this to show the file name.
amazon_s3 is your shortcode containing $atts bucket and object
when you use wordpress function add_shortcode('amazon_s3', 'your_function_name');
it automatically converts your attributes defined in [amazan_s3 .... to $atts
e.g.
function your_funnction_name($atts) {
extract(shortcode_atts(array(
'bucket' => '',
'object' => ''
), $atts));
return $object;
}

Resources