即使我们创建了图像大小,我们也需要额外的代码将其添加到可用大小的媒体上传器下拉列表中。首先,让我们注册大小。我们可以使用init
或after_setup_theme
挂钩:
function theme_init() {
add_image_size( \'banner_image\', 1200, 200, true );
}
add_action( \'init\', \'theme_init\' );
我们需要使用
image_size_names_choose
钩子将新尺寸添加到可用尺寸中。这个
Developer Resources suggests 使用以下各项:
/**
* @param Array $default_sizes - Array( \'size_slug\' => \'Size Title\' )
*
* @return Array $default_sizes
*/
function image_sizes_to_mediapicker( $default_sizes ) {
return array_merge( $default_sizes, array(
\'banner_image\' => __( \'Banner Image\' ),
) );
}
add_filter( \'image_size_names_choose\', \'image_sizes_to_mediapicker\' );
上面的操作很好,但也许我们可以将其自动化一点。下面假设任何额外的大小都是用下划线命名的,因此它可能不是与添加自己大小的插件一起工作的最佳解决方案。它还被大量注释,以显示每个变量是什么。
/**
* @param Array $default_sizes - Array( \'size_slug\' => \'Title\' )
*
* @return Array $return_sizes
*/
function image_sizes_to_mediapicker( $default_sizes ) {
global $_wp_additional_image_sizes; // All additionally added sizes
$size_slugs = array_keys( $_wp_additional_image_sizes ); // Get array of additional sizes
$default_slugs = array_keys( $default_sizes ); // Get array of default sizes
$exclude_sizes = array( \'medium_large\' ); // Exclude any image sizes
// $exclude_sizes = get_option( \'mediapicker_exlcuded_sizes\', array() ) // IF we want to previously set / retrieve an array of excluded options
$sizes_needed = array_diff( $size_slugs, $default_slugs, $exclude_sizes ); // Get difference between the defaults and additional sizes
$return_sizes = $default_sizes; // Let\'s keep separation between passed and returned
foreach( $sizes_needed as $size_slug ) {
$pretty_title = ucwords( str_replace( \'_\', \' \', $size_slug ) ); // Create a pretty title
$return_sizes[ $size_slug ] = __( $pretty_title );
}
return $return_sizes;
}
add_filter( \'image_size_names_choose\', \'image_sizes_to_mediapicker\' );