I am using the default post type and category taxonomy to manage the content on an in-development website that is using WordPress multisite. There are categories defined like "bylaws" and "minutes" that need to be added to the file uploads when completed through the WordPress post editor interface. The full file paths after a successful upload should look like the following: https://domain.com/site-name/wp-content/uploads/sites/site-id/taxonomy/file-name.ext
.
Note: I have set uploads_use_yearmonth_folders
to 0 on the site's settings tab.
I have the following code in my theme's functions file. The code works when I hard code a value like "customdir", but the global $post
and terms
are not being retrieved.
function add_taxonomy_to_upload_dir( $upload ) {
// Get the current post ID
global $post; // The post object is not being retrieved
$post_id = $post->ID;
$custom_dir = 'customdir';
if ( isset( $post_id ) && ! empty( $post_id ) ) {
$taxonomy = 'category';
// Get the terms associated with the post
$terms = get_the_terms( $post_id, $taxonomy );
if ( $terms && ! is_wp_error( $terms ) ) {
// Use the first term found
// Posts should only have one category assigned
$term = array_shift( $terms );
// Add the taxonomy name to the uploads path
$upload['path'] = $upload['path'] . '/' . $term->slug; // Does not work
$upload['url'] = $upload['url'] . '/' . $term->slug; // Does not work
}
}
$upload['path'] = $upload['path'] . '/' . $custom_dir; // This works
$upload['url'] = $upload['url'] . '/' . $custom_dir; // This works
return $upload;
}
add_filter( 'upload_dir', 'add_taxonomy_to_upload_dir' );
I have tested with the global $post
variable inside and outside of the function.