Hello Greg
Here are 3 other examples which is best to work, thanks a lot
function custom_upload_path( $path ) {
// Check if it's a post-related upload, from the media library, or from WP Adverts
$is_upload_attachment = !empty( $_REQUEST['action'] ) && $_REQUEST['action'] === 'upload-attachment';
$is_wp_adverts_upload = ( isset( $_REQUEST['page'] ) && $_REQUEST['page'] === 'adverts' ) || ( isset( $_REQUEST['adverts-action'] ) && $_REQUEST['adverts-action'] === 'upload' );
if ( $is_upload_attachment || $is_wp_adverts_upload ) {
$upload_year = date('Y');
$new_path = WP_CONTENT_DIR . '/uploads/content-images/' . $upload_year;
$path['subdir'] = '/content-images/' . $upload_year;
$path['path'] = $new_path . $path['subdir'];
$path['url'] = $path['url'] . $path['subdir'];
}
return $path;
}
add_filter( 'upload_dir', 'custom_upload_path' );
function custom_upload_path( $path ) {
// Check for post uploads, media library uploads, or WP Adverts frontend uploads
if ( !empty( $_SERVER['HTTP_REFERER'] ) && (
strpos( $_SERVER['HTTP_REFERER'], 'post.php' ) !== false || // Post-related uploads
strpos( $_SERVER['HTTP_REFERER'], 'upload.php' ) !== false || // Media library uploads
strpos( $_SERVER['HTTP_REFERER'], 'adverts_add' ) !== false // WP Adverts frontend uploads
) ) {
$upload_year = date('Y');
$new_path = WP_CONTENT_DIR . '/uploads/content-images/' . $upload_year;
// Ensure directory exists
if ( !wp_mkdir_p( $new_path ) ) {
wp_die( __( 'Failed to create content images directory.' ) );
}
$path['subdir'] = '/content-images/' . $upload_year;
$path['path'] = $new_path . $path['subdir'];
$path['url'] = $path['url'] . $path['subdir'];
}
return $path;
}
add_filter( 'upload_dir', 'custom_upload_path' );
function custom_upload_path( $path ) {
// Check if it's a post-related upload, from the media library, or from WP Adverts with the field name "gallery"
$is_upload_attachment = !empty( $_REQUEST['action'] ) && $_REQUEST['action'] === 'upload-attachment';
$is_wp_adverts_gallery_upload = ( isset( $_REQUEST['page'] ) && $_REQUEST['page'] === 'adverts' && isset( $_REQUEST['field_name'] ) && $_REQUEST['field_name'] === 'gallery' )
|| ( isset( $_REQUEST['adverts-action'] ) && $_REQUEST['adverts-action'] === 'upload' && isset( $_REQUEST['field_name'] ) && $_REQUEST['field_name'] === 'gallery' );
if ( $is_upload_attachment || $is_wp_adverts_gallery_upload ) {
$upload_year = date('Y');
$new_path = WP_CONTENT_DIR . '/uploads/content-images/' . $upload_year;
$path['subdir'] = '/content-images/' . $upload_year;
$path['path'] = $new_path . $path['subdir'];
$path['url'] = $path['url'] . $path['subdir'];
}
return $path;
}
add_filter( 'upload_dir', 'custom_upload_path' );
Thanks