【问题标题】:How to Change Image Attributes in WordPress Posts如何更改 WordPress 帖子中的图像属性
【发布时间】:2017-09-24 21:10:30
【问题描述】:

Wordpress 帖子显示以下图片结果。

<img class="large alignnone size-full wp-image-8" src="http://localhost/blog/wp-content/uploads/2017/04/t-radio-city-music-hall.jpg" alt="" width="960" height="654" srcset="http://localhost/blog/wp-content/uploads/2017/04/t-radio-city-music-hall.jpg 960w, http://localhost/blog/wp-content/uploads/2017/04/t-radio-city-music-hall-300x204.jpg 300w, http://localhost/blog/wp-content/uploads/2017/04/t-radio-city-music-hall-768x523.jpg 768w" sizes="(max-width: 960px) 100vw, 960px">

我怎样才能改变这些输出如下?

  • 删除 srcset
  • 将 src 替换为原始数据

最终结果应该有属性:data-original、classes、width、height。

需要 WordPress 查询。

请不要使用 jQuery。

【问题讨论】:

    标签: php wordpress image src wordpress-hook


    【解决方案1】:

    WordPress 有一个内置的钩子来修改或更改图像 HTML wp_get_attachment_image_attributes.

    代码如下:

    function wh_alter_attachment_image($attr)
    {
        if (isset($attr['srcset']))
            unset($attr['srcset']);
        if (isset($attr['src']))
        {
            $attr['data-original'] = $attr['src'];
            unset($attr['src']);
        }
        return $attr;
    }
    
    add_filter('wp_get_attachment_image_attributes', 'wh_alter_attachment_image');
    

    代码进入您的活动子主题(或主题)的functions.php 文件。或者也可以在任何插件 php 文件中。
    代码已经过测试并且可以工作。

    希望这会有所帮助!

    【讨论】:

    • 我正在尝试运行代码,但它根本没有改变任何东西。我正在使用 WP 最新版本 4.7.4
    • 我只测试了最新版本,然后你需要调试,print_r($attr) 看看你得到了什么。
    • 当我点击图片并转到独立页面时,您的代码在此处工作,但在我附加了许多图片的页面上不起作用。
    • 此过滤器不能用于帖子中的所有图像,它们都被视为数据库中的附件(帖子类型 - 附件),但它实际上是为特色图像/帖子缩略图保留的。
    • 另外需要注意的是,这个功能不再运行在带有块编辑器的前端。 github.com/WordPress/gutenberg/issues/13661
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2020-11-06
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多