images – Change attachments name

Question

What I have to do is to update filename for existing attachments and for the upcoming attachments. The problems/questions are:

  1. if I update attachments of existing posts, I have to update post_title, post_name and guid in the wp_posts? And how can I make it for the guid?
  2. The function used for upcoming posts works well, but, all upcoming images stop scaling.

The script used for update curent attachsments:

<?php 
require_once( '../../../wp-load.php' );

$args = array(
    'post_type' => 'attachment',
    'orderby' => 'date', 
    'order' => 'DESC', 
    'posts_per_page' => 50
);
$attachments = get_posts($args);
foreach($attachments as $att){
    $getPost = get_post($att->ID);
    $getParentPost = get_post($getPost->post_parent);
    $getPostParentTitle = $getParentPost->post_name;

    $file = get_attached_file($att->ID);
    $path = pathinfo($file);

    $newfilename = $getPostParentTitle . "-" . $att->ID;
    $newfile = $path['dirname']."/".$newfilename.".".$path['extension'];

    // update post title and post name of the attachments
    // wp_update_post(array ('ID'=> $att->ID,'post_name'=> $getPostParentTitle));
    // wp_update_post(array ('ID'=> $att->ID,'post_title'=> $getPostParentTitle));

    // rename file
    rename($file, $newfile);    
    update_attached_file( $att->ID, $newfile );
}

In the functions.php, the function for the upcoming posts:

add_action('add_attachment', 'rename_attachment');
function rename_attachment($post_ID){
    $getPost = get_post($post_ID);
    $getParentPost = get_post($getPost->post_parent);
    $getPostParentTitle = $getParentPost->post_title;

    $file = get_attached_file($post_ID);
    $path = pathinfo($file);

    $newfilename = $getPostParentTitle . "_" . $post_ID;
    $newfile = $path['dirname']."/".$newfilename.".".$path['extension'];

    rename($file, $newfile);    
    update_attached_file( $post_ID, $newfile );
}

0
Mike 5 months 2022-03-23T05:57:41-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse