custom post types – Changing upload directory and migrating old attachments

Question

I have a requirement, for that, I have to change a CPT’s upload folder, which I have achieved by the following code.

add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' );
function rsg_pre_upload( $file ) {
    add_filter( 'upload_dir', 'rsg_custom_upload_dir' );
    return $file;
}

function rsg_custom_upload_dir( $param ) {
    $id = $_REQUEST['post_id'];
    $parent = get_post( $id )->post_parent;
    if( "hg-agencies" == get_post_type( $id ) || "hg-agencies" == get_post_type( $parent ) ) {
        $mydir="/hg-uploads";
        $param['path'] = $param['basedir'] . $mydir;
        $param['url']  = $param['baseurl'] . $mydir;
    }
    return $param;
}

This works fine, but the issue is, that the CPT is in use for a while and have a lot of attachments, ie featured image and images/pdfs uploaded via custom meta boxes, etc. So how can I migrate all those attachments to a new folder structure, If I manually copy those old attachments to new locations how can I update the attachment URL associated with the posts? For new uploads, it works, so if I do a manual re-upload for all the posts in this CPT this will work, but that is a difficult task to do for a lot of posts. So any solutions or suggestions will help a lot.

0
Salih K 4 weeks 2022-09-02T00:33:57-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse