Загружаем файлы кастомных постов в отдельные папки и подпапки


С помощью чудесмного плагина Toolset Types создаем свой кастомны тип постов и дальше для него создаем кастомную таксономию (типа категорию). В моем случае тип поста был gallery, а таксономию категории была gallery-cat.

Далее была найдена чудесная функция Post type specific upload folder - немного ее доработав наши файлы начали загружаться еще и в подпапки соответствующей категории ) Привожу финальный вариант:

add_filter('upload_dir', 'cgg_upload_dir');
function cgg_upload_dir($dir)
{
    // xxx Lots of $_REQUEST usage in here, not a great idea.

    // Are we where we want to be?
    if (!isset($_REQUEST['action']) || 'upload-attachment' !== $_REQUEST['action']) {
        return $dir;
    }

    // make sure we have a post ID
    if (!isset($_REQUEST['post_id'])) {
        return $dir;
    }

    // modify the path and url.
    $type = get_post_type($_REQUEST['post_id']);
	
	$cats = get_the_terms($_REQUEST['post_id'], 'gallery-cat', array("fields" => "all"));
	foreach($cats as $cats_sl) {
		$gal_subdir = $cats_sl->slug;
	}
	if(!empty($gal_subdir)) {
		$uploads = apply_filters("{$type}_upload_directory", $type."/".$gal_subdir);
	} else {
		$uploads = apply_filters("{$type}_upload_directory", $type);
	}
    $dir['path'] = path_join($dir['basedir'], $uploads);
    $dir['url'] = path_join($dir['baseurl'], $uploads);

    return $dir;
}

кстати, для оформления кастомных постов очень помог плагин Custom Post Type Permalinks - с его помощью для кастомного поста gallery указал свой урл с учетом категорий:

/%gallery-cat%/%post_id%-%postname%.html

ну и не забыаем про обязательный плагин перевода кирилицы в латиницу (для ссылок) Cyr to Lat enhanced

ПОЛЕЗНО  Load a script just to custom post type in admin

Custom Upload Directories for Post Types

// Custom Upload Directories for Post Types
 
add_filter( 'upload_dir', 'custom_upload_directory' );
function custom_upload_directory( $args ) {
 
    $id = $_REQUEST['post_id'];
    $parent = get_post( $id )->post_parent;
    $slug = get_post( $id )->post_name;
 
    // Check the post-type of the current post
    // assign directory to upload to
    // assign URL to connect to
    if( "gallery" == get_post_type( $id ) || "gallery" == get_post_type( $parent ) ) {
		$cats = get_the_terms($_REQUEST['post_id'], 'gallery-cat', array("fields" => "all"));
		foreach($cats as $cats_sl) {
			$slug = $cats_sl->slug;
		}
        $args['path'] = WP_CONTENT_DIR . '/uploads/gallery/' . $slug . '';
        $args['url']  = WP_CONTENT_URL . '/uploads/gallery/' . $slug . '';
    }
    if( "photograph" == get_post_type( $id ) || "photograph" == get_post_type( $parent ) ) {
        $args['path'] = WP_CONTENT_DIR . '/uploads/photograph/' . $slug . '';
        $args['url']  = WP_CONTENT_URL . '/uploads/photograph/' . $slug . '';
    }
    if( "other-artwork" == get_post_type( $id ) || "other-artwork" == get_post_type( $parent ) ) {
        $args['path'] = WP_CONTENT_DIR . '/uploads/other-artwork/' . $slug . '';
        $args['url']  = WP_CONTENT_URL . '/uploads/other-artwork/' . $slug . '';
    }
    return $args;
}

у меня он сработал лучше. после него я добавил плагин Set All First Images As Featured и в нем подправил функционал, что если нет картинок в самом посте, то пробовать искать еще в кастомном поле. правилось вот тут: wp-content\plugins\set-all-first-images-as-featured\includes\class-core.php

ПОЛЕЗНО  Имена загружаемых файлов как заголовок поста

ищем кусок кода

		$result  = new stdClass();
		$pattern = '@<img.+src="(?P<SRC>.*)".*>@Uims';
		$str     = $item->post_content;
		
		preg_match($pattern, $str, $matches);

и ниже дописываем

		if( empty($matches) ) {
			$matches['SRC'] = get_post_meta($item->ID, 'wpcf-gallery-photo', true);
		}

понятное дело, что URK на полное фото у меня находится в кастомном поле wpcf-gallery-photo