我的WordPress媒体库中存储了一堆图像。通过使用WordPress UI为其中的每一个都指定了一个alt文本,如下所示:

我正在尝试从我的php模板文件中获取图像的alt文本。我到底该怎么做呢?
我知道我可以使用get_template_directory_uri()方法获取URL
<img src="<?php echo get_template_directory_uri(); ?>/path/to/logo/logo.png">但是,我如何在媒体库中获取图像的alt文本呢?
发布于 2021-11-03 05:39:54
我已经写了一个函数来做这件事。
将此函数添加到您的functions.php.
function image_alt_by_url($image_url) {
$image_id = attachment_url_to_postid($image_url);
$alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);
return $alt;
}在您的模板中,以图像url为参数值调用此函数。
echo image_alt_by_url( get_template_directory_uri().'/path/to/logo/logo.png' );https://stackoverflow.com/questions/51554589
复制相似问题