我想在主站点上对图像使用alt属性标签。
我使用的代码要求最新的wordpress帖子在索引页上显示图片。我将此代码用于index.php
:
<a href="<?php the_permalink() ?>"><img src="<?php echo catch_that_image() ?>" width="250" alt=""></a>
functions.php
文件中用于捕获该图像的代码是:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
我想要实现的是从该帖子中获取alt
标签,而不仅仅是图像。实际上是某种“抓住那个替代”。 index.php
中的新代码应为
<a href="<?php the_permalink() ?>"><img src="<?php echo catch_that_image() ?>" width="250" alt="text from wordpress post"></a>
如何为functions.php
添加任何内容,以使替代文本在一起?
目的是使Google经常搜索图像,而在主要网站上却找不到alt标签,而仅在单个wordpress帖子上找不到。
答案 0 :(得分:0)
您可以在functions.php中添加以下代码以启用该功能。
function add_img_title($attr, $attachment = null) {
$img_title = trim(strip_tags($attachment->post_title));
$attr['alt'] = $img_title;
$attr['title'] = $img_title;
return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'add_img_title', 10, 2);