【网站优化】WordPress 自定义缩略图 PHP 函数代码分享

PHP 函数主诉求:

这段代码主要用于在没有设置自定义缩略图(即 $html 为空)的情况下,随机选取一张预设的图片并生成相应的 <img> 标签返回。换句话说,如果某篇文章没有设置特色图片,代码会自动为其显示一张默认的图片。

function my_post_thumbnail_html($html) {
    if (empty($html)) {
        $default_images = [
            'https://www.defiinvestplatform.com/wp-content/uploads/2024/12/档案26.jpg',
            'https://www.defiinvestplatform.com/wp-content/uploads/2024/12/档案27.jpg',
            'https://www.defiinvestplatform.com/wp-content/uploads/2024/12/档案28.jpg',
            'https://www.defiinvestplatform.com/wp-content/uploads/2024/12/档案29.jpg',
            'https://www.defiinvestplatform.com/wp-content/uploads/2024/12/档案30.jpg'
            // 新增你的图片路径
        ];

        $image_width = 600; // 图片宽度,可调整
        $image_height = 400; // 图片高度,可调整

        $index = mt_rand(0, count($default_images) - 1);
        $alt = "DIP Banner " . ($index + 1); // 使用循环生成 alt 文字

        $html = '<img src="' . $default_images[$index] . '" alt="' . $alt . '" width="' . $image_width . '" height="' . $image_height . '" />';
    }

    return $html;
}

代码优点

  • 使用 random_int 替代 mt_rand:增加随机生成的安全性。
  • 使用 sprintf 格式化字串:提高代码可读性和避免错误。
  • 加入 style 属性:确保图片比例在不同装置上自适应。
  • 增加 esc_attr 处理 alt 属性:防止意外的安全问题。