如何实现og:title随随机图片文件名自动变更?
如何让og:title自动匹配当前显示图片的文件名?
嘿,这个需求很好实现,咱们只需要在现有代码里加几行,把选中图片的文件名提取出来,再赋值给og:title的content属性就可以了。
具体步骤:
- 提取图片文件名:拿到
$file_1(当前选中的图片路径)后,用PHP的basename()函数提取纯文件名——这个函数可以帮我们去掉路径和文件后缀(比如.jpg)。 - 将文件名赋值给og:title:把提取到的文件名变量替换掉原来
og:title里的固定文本。
修改后的完整代码:
<?php function random_pic($dir, $nf=3) { $files = glob($dir . DIRECTORY_SEPARATOR . '*.jpg'); shuffle($files); return array_pop($files); } //$number = rand(); ?v=$number $path = 'images'; $file_1 = random_pic($path, 1); // 新增:提取不带路径和后缀的文件名 $image_title = basename($file_1, '.jpg'); $image = file_get_contents($file_1); $og_img = base64_encode($image); ?> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 这里把固定标题换成提取到的文件名变量 --> <meta property="og:title" content="<?php echo $image_title; ?>" /> <meta property="og:type" content="article" /> <meta property="og:url" content="http://YourDomain.com" /> <meta property="og:image" content="http://YourDomain.com/<?php echo $file_1 ?>" />
补充说明:
如果你的图片还有其他格式(比如.png),可以用更通用的方式提取文件名,适配所有格式:
// 通用提取文件名(适配所有图片格式) $full_filename = basename($file_1); $image_title = pathinfo($full_filename, PATHINFO_FILENAME);
这样不管是jpg还是png,都能正确提取不带后缀的文件名。
内容的提问来源于stack exchange,提问作者Chhibo
相关产品推荐
相关产品推荐

