如何在WP_IMAGE_EDITOR中获取当前图像的插件?

时间:2017-02-07 作者:Johansson

我一直在编写一些类和函数来修改缩略图的路径。我扩展了原来的WP_Image_Editor 类来实现自定义结构。

What i want: 根据缩略图的slug,将缩略图存储在upload目录中的不同文件夹中。例如:http://example.com/uploads/medium/image.jpg

What i have already done:

class WP_Image_Editor_Custom extends WP_Image_Editor_GD {
    public function generate_filename($prefix = NULL, $dest_path = NULL, $extension = NULL) {
        global $current_size_slug;
        // If empty, generate a prefix with the parent method get_suffix().
        if(!$prefix)
            $prefix = $this->get_suffix();

        // Determine extension and directory based on file path.
        $info = pathinfo($this->file);
        $dir  = ABSPATH."/media/";
        $ext  = $info[\'extension\'];

        // Determine image name.
        $name = wp_basename($this->file, ".$ext");

        // Allow extension to be changed via method argument.
        $new_ext = strtolower($extension ? $extension : $ext);

        // Default to $_dest_path if method argument is not set or invalid.
        if(!is_null($dest_path) && $_dest_path = realpath($dest_path))
            $dir = $_dest_path;

        // Return our new prefixed filename.
        $slug = $current_size_slug; 
        return trailingslashit($dir)."{$slug}/{$name}.{$new_ext}";
    }
    function multi_resize($sizes) {
        $sizes = parent::multi_resize($sizes);
        foreach($sizes as $slug => $data)
            $sizes[$slug][\'file\'] = $slug."/".$data[\'file\'];
            $current_size_slug = $slug;
        return $sizes;
    }
}
上载图像时,缩略图创建正确,但文件名不正确。这个$slug 值未从传递multi_resize() 生成\\\\u文件名。

我试着写multi_resize() 功能如下:

class WP_Image_Editor_Custom extends WP_Image_Editor_GD {
    public function generate_filename($prefix = NULL, $dest_path = NULL, $extension = NULL) {
        global $current_size_slug;
        // If empty, generate a prefix with the parent method get_suffix().
        if(!$prefix)
            $prefix = $this->get_suffix();

        // Determine extension and directory based on file path.
        $info = pathinfo($this->file);
        $dir  = ABSPATH."/media/";
        $ext  = $info[\'extension\'];

        // Determine image name.
        $name = wp_basename($this->file, ".$ext");

        // Allow extension to be changed via method argument.
        $new_ext = strtolower($extension ? $extension : $ext);

        // Default to $_dest_path if method argument is not set or invalid.
        if(!is_null($dest_path) && $_dest_path = realpath($dest_path))
            $dir = $_dest_path;

        // Return our new prefixed filename.
        $slug = $current_size_slug; 
        return trailingslashit($dir)."{$slug}/{$name}.{$new_ext}";
    }
    function multi_resize($sizes) {
        $sizes = parent::multi_resize($sizes);
        foreach($sizes as $slug => $data)
            $sizes[$slug][\'file\'] = $slug."/".$data[\'file\'];
            $current_size_slug = $slug;
        return $sizes;
    }
}
现在$slug 已传递给generate_filename() 但缩略图都是在uploads文件夹中生成的,相互覆盖。我该怎么做?

我在这里不知所措,非常感谢您的帮助。

2 个回复
最合适的回答,由SO网友:David Lee 整理而成

尝试将其添加到函数中。php:

add_filter("wp_image_editors", "my_wp_image_editors");

function my_wp_image_editors($editors) {
    array_unshift($editors, "WP_Image_Editor_Custom");
    return $editors;
}

// Include the existing classes first in order to extend them.
require_once ABSPATH . WPINC . "/class-wp-image-editor.php";
require_once ABSPATH . WPINC . "/class-wp-image-editor-gd.php";

class WP_Image_Editor_Custom extends WP_Image_Editor_GD {

    public function generate_filename($suffix = null, $dest_path = null, $extension = null) {
        // $suffix will be appended to the destination filename, just before the extension
        if (!$suffix) {
            $suffix = $this->get_suffix();
        }

        $dir = pathinfo($this->file, PATHINFO_DIRNAME);
        $ext = pathinfo($this->file, PATHINFO_EXTENSION);

        $name = wp_basename($this->file, ".$ext");
        $new_ext = strtolower($extension ? $extension : $ext );

        if (!is_null($dest_path) && $_dest_path = realpath($dest_path)) {
            $dir = $_dest_path;
        }
        //we get the dimensions using explode, we could have used the properties of $this->file[height] but the suffix could have been provided
        $size_from_suffix = explode("x", $suffix);
        //we get the slug_name for this dimension
        $slug_name = $this->get_slug_by_size($size_from_suffix[0], $size_from_suffix[1]);

        return trailingslashit($dir) . "{$slug_name}/{$name}.{$new_ext}";
    }

    function multi_resize($sizes) {
        $sizes = parent::multi_resize($sizes);

        //we add the slug to the file path
        foreach ($sizes as $slug => $data) {
            $sizes[$slug][\'file\'] = $slug . "/" . $data[\'file\'];
        }

        return $sizes;
    }

    function get_slug_by_size($width, $height) {

        // Make thumbnails and other intermediate sizes.
        $_wp_additional_image_sizes = wp_get_additional_image_sizes();

        $image_sizes = array(); //all sizes the default ones and the custom ones in one array
        foreach (get_intermediate_image_sizes() as $s) {
            $image_sizes[$s] = array(\'width\' => \'\', \'height\' => \'\', \'crop\' => false);
            if (isset($_wp_additional_image_sizes[$s][\'width\'])) {
                // For theme-added sizes
                $image_sizes[$s][\'width\'] = intval($_wp_additional_image_sizes[$s][\'width\']);
            } else {
                // For default sizes set in options
                $image_sizes[$s][\'width\'] = get_option("{$s}_size_w");
            }

            if (isset($_wp_additional_image_sizes[$s][\'height\'])) {
                // For theme-added sizes
                $image_sizes[$s][\'height\'] = intval($_wp_additional_image_sizes[$s][\'height\']);
            } else {
                // For default sizes set in options
                $image_sizes[$s][\'height\'] = get_option("{$s}_size_h");
            }

            if (isset($_wp_additional_image_sizes[$s][\'crop\'])) {
                // For theme-added sizes
                $image_sizes[$s][\'crop\'] = $_wp_additional_image_sizes[$s][\'crop\'];
            } else {
                // For default sizes set in options
                $image_sizes[$s][\'crop\'] = get_option("{$s}_crop");
            }
        }
        $slug_name = ""; //the slug name

        if($width >= $height){
          foreach ($image_sizes as $slug => $data) { //we start checking
            if ($data[\'width\'] == $width) {//we use only width because regardless of the height, the width is the one used for resizing in all cases with crop 1 or 0
                $slug_name = $slug;
            }
            /*
             * There could be custom added image sizes that have the same width as one of the defaults so we also use height here
             * if there are several image sizes with the same width all of them will override the previous one leaving the last one, here we get also the last one
             * since is looping the entire list, the height is used as a max value for non-hard cropped sizes
             *  */
              if ($data[\'width\'] == $width && $data[\'height\'] == $height) {
                  $slug_name = $slug;
              }
          }
         }else{
           foreach ($image_sizes as $slug => $data) {
              if ($data[\'height\'] == $height) {
                  $slug_name = $slug;
              }
              if ($data[\'height\'] == $height && $data[\'width\'] == $width ) {
                  $slug_name = $slug;
              }
            }
         }
        return $slug_name;
    }
}
我知道您已经知道几乎所有这些代码,请注意generate_filename 函数已更新为当前函数,您将对get_slug_by_size 功能,这是您缺少的关键部分。这也适用于自定义图像大小,如下所示:

enter image description here

home-bottom 是我添加的图像大小。目前wordpress有4种不同的默认图像大小:

    Array
    (
        [thumbnail] => Array // Thumbnail (150 x 150 hard cropped)
            (
                [width] => 150
                [height] => 150
                [crop] => 1
            )

        [medium] => Array // Medium resolution (300 x 300 max height 300px)
            (
                [width] => 300
                [height] => 300
                [crop] => 
            )

        [medium_large] => Array //Medium Large (added in WP 4.4) resolution (768 x 0 infinite height)
            (
                [width] => 768
                [height] => 0
                [crop] => 
            )

        [large] => Array // Large resolution (1024 x 1024 max height 1024px)
            (
                [width] => 1024
                [height] => 1024
                [crop] => 
            )

    )
// Full resolution (original size uploaded) this one is not in the array.
如果您上载width 310 只有thumbnailmedium 将创建图像WordPress不会创建更大的图像,因此使用上面的代码,只会创建2个文件夹。

SO网友:user6552940

解释其用例的代码示例将更有帮助。不确定您将如何使用它,但要简单地访问$size中的所有slug,您可以使用它

multi\\u resize()获取其“大小”作为参数,该参数由wp\\u generate\\u attachment\\u metadata()提供here. 获取sizes数组的一种简单方法是将其存储在类属性中。例如

将此添加到所有函数之前。

public $current_size_slug = \'\';
这是generate\\u filename()函数,需要进行必要的修改和注释,以帮助您了解其工作原理:

public function generate_filename( $prefix = null, $dest_path = null, $extension = null ) {
// <-- Now we have the current thumbnail slug.-->
$slug = $this->current_size_slug;
// If empty, generate a prefix with the parent method get_suffix().
if ( ! $prefix ) {
    $prefix = $this->get_suffix();
}

// Determine extension and directory based on file path.
$info = pathinfo( $this->file );
$dir  = $info[\'dirname\'];
$ext  = $info[\'extension\'];

// Determine image name.
$name = wp_basename( $this->file, ".$ext" );

// Allow extension to be changed via method argument.
$new_ext = strtolower( $extension ? $extension : $ext );

// Default to $_dest_path if method argument is not set or invalid.
if ( ! is_null( $dest_path ) && $_dest_path = realpath( $dest_path ) ) {
    $dir = $_dest_path;
}

// Return our new prefixed filename.
// <-- Replaced prefix with slug. -->
return trailingslashit( $dir ) . "{$slug}/{$name}.{$new_ext}"; 

}
此multi\\u resize()函数在调用\\u save()之前实际设置$current\\u size\\u slug

function multi_resize( $sizes ) {
$metadata  = array();
$orig_size = $this->size;

foreach ( $sizes as $size => $size_data ) {
    if ( ! isset( $size_data[\'width\'] ) && ! isset( $size_data[\'height\'] ) ) {
        continue;
    }

    if ( ! isset( $size_data[\'width\'] ) ) {
        $size_data[\'width\'] = null;
    }
    if ( ! isset( $size_data[\'height\'] ) ) {
        $size_data[\'height\'] = null;
    }

    if ( ! isset( $size_data[\'crop\'] ) ) {
        $size_data[\'crop\'] = false;
    }

    $image     = $this->_resize( $size_data[\'width\'], $size_data[\'height\'], $size_data[\'crop\'] );
    $duplicate = ( ( $orig_size[\'width\'] == $size_data[\'width\'] ) && ( $orig_size[\'height\'] == $size_data[\'height\'] ) );

    if ( ! is_wp_error( $image ) && ! $duplicate ) {
        // We set the current slug before calling the save function.
        $this->current_size_slug = $size;

        $resized = $this->_save( $image );

        imagedestroy( $image );

        if ( ! is_wp_error( $resized ) && $resized ) {
            unset( $resized[\'path\'] );
            $metadata[ $size ] = $resized;
        }
    }

    $this->size = $orig_size;
}

return $metadata;
}
函数的作用是将文件保存在服务器上,为此调用generate\\u filename()。我希望这能回答你的问题
如果您对PHP和WordPress不太熟悉,请考虑聘请一名开发人员从事此类定制工作Not 除非您知道自己在做什么,否则请复制并粘贴代码。

相关推荐

Remove <p></p> after images

我对<p></p> 出现在my之后的标记<img....>. 以下是我在本地主机上查看生成的页面时显示的内容。。。<img src=\"/wp-content/themes/wunderful/assets/images/feedback-danielle.png\" alt=\"Danielle Johnson Deal Town FC Treasurer\"> <p></p> 请注意随机生成的<p>&