【问题标题】:Wordpress , display resized image in theme with PHPWordpress,使用 PHP 在主题中显示调整大小的图像
【发布时间】:2014-10-08 21:45:33
【问题描述】:

我正在编写一个短代码,它接受一个媒体 ID 作为属性。然后,此短代码应以使用 add_image_size 注册的现有大小显示图像。 问题:我的图片显示的尺寸不正确。

说明:

  • 我的媒体图片已上传到 WP 库中。原始文件大小很大(1227x924)。媒体的 ID 为 294。

  • 我在functions.php中注册了一个图片尺寸:

    function my_after_setup_theme(){  
        add_image_size('my-image-size', 210, 136, true);  
    }  
    add_action('after_setup_theme', 'my_after_setup_theme');
    
  • 我在我的一个页面中插入了我的简码:[my_shortcode imageid="294"]

  • 我的简码是:

    function my_shortcode_func($atts)
    {
        $a = shortcode_atts(array(
            'imageid'    => 0,
        ), $atts);
        if ($a['imageid'] == 0) {
            // default placeholder image
            $img = 'img src="http://placehold.it/210x136"/>';
        } else {
            // get resized  (NOT WORKING !)
            $img = wp_get_attachment_image($a['imageid'], 'my-image-size');
        }
        return $img;
    }
    add_shortcode('my_shortcode', 'my_shortcode_func');
    
  • 我希望在新的缩略图文件中以正确的大小(即:210x136)调整原始图像的大小。相反,$img 显示原始图像 (1227x924) ,通过 HTML <img> 标记的宽度和高度属性以中间尺寸显示:

我做错了什么?

感谢您的帮助。

【问题讨论】:

  • 返回 $img 的输出究竟是什么?

标签: wordpress


【解决方案1】:

您是否在上传媒体后注册了缩略图大小?如果是这样,您将需要使用插件来重新生成缩略图。

此外,我认为您不需要像您所做的那样包装缩略图大小声明,我有以下内容;

if (function_exists('add_theme_support'))
{
   add_theme_support('post-thumbnails'); // Featured image support for posts - you may not need this bit.
   add_image_size('large', 700, '', true); // Large Thumbnail - This is the bit you would need
} 

因此,如果您的缩略图实际上是从一开始就生成的,那么值得检查一下,因为我从来没有按照您在问题中定义的方式这样做。

【讨论】:

  • 你是对的!我使用了 Regenerate Thumbnails 插件,一切正常……谢谢!虽然我觉得这种行为有点奇怪......如果图像不存在,函数 wp_get_attachment_image 会即时重新生成图像。
猜你喜欢
  • 1970-01-01
  • 2011-06-16
  • 1970-01-01
  • 2012-08-15
  • 2017-06-21
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多