ارسال تصاویر نوشتهها و برگهها به پوشههای جداگانه
این کد تصاویر آپلودشده در نوشتهها و برگههای وردپرس را در پوشههای جداگانه ذخیره میکند.
تصاویر نوشتهها در پوشه post-image ذخیره میشوند.
تصاویر برگهها در پوشه page-image ذخیره میشوند.
نام فایل تصویر بر اساس عنوان نوشته یا برگه تعیین میشود.
فاصلههای موجود در عنوان به – تبدیل میشوند.
برای سایر انواع محتوا، مسیر پیشفرض آپلود وردپرس بدون تغییر باقی میماند.
<?php
function custom_upload_dir_for_posts_and_pages( $upload ) {
if ( empty($_REQUEST['post_id']) ) {
return $upload;
}
$post_id = (int) $_REQUEST['post_id'];
$post_type = get_post_type( $post_id );
if ( $post_type === 'post' ) {
$custom_dir = '/post-image';
} elseif ( $post_type === 'page' ) {
$custom_dir = '/page-image';
} else {
return $upload;
}
$upload['subdir'] = $custom_dir;
$upload['path'] = $upload['basedir'] . $custom_dir;
$upload['url'] = $upload['baseurl'] . $custom_dir;
return $upload;
}
add_filter( 'upload_dir', 'custom_upload_dir_for_posts_and_pages' );
function custom_rename_uploaded_file( $file ) {
if ( empty($_REQUEST['post_id']) ) {
return $file;
}
$post_id = (int) $_REQUEST['post_id'];
$post = get_post( $post_id );
if ( ! $post || ! in_array( $post->post_type, ['post', 'page'] ) ) {
return $file;
}
$title = trim( $post->post_title );
if ( empty( $title ) ) {
return $file;
}
$title = preg_replace('/[^\p{Arabic}\p{L}\p{N}\s\-_]/u', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$extension = pathinfo( $file['name'], PATHINFO_EXTENSION );
$file['name'] = $title . '.' . $extension;
return $file;
}
add_filter( 'wp_handle_upload_prefilter', 'custom_rename_uploaded_file' );