【问题标题】:How to get specific image alt text from WordPress media library?如何从 WordPress 媒体库中获取特定的图像替代文本?
【发布时间】:2021-11-03 13:45:52
【问题描述】:

我的 WordPress 媒体库中存储了一堆图像。每个都使用 WordPress UI 分配了一个替代文本,如下所示:

我正在尝试从我的 php 模板文件中获取图像替代文本。我该怎么做?

我知道我可以使用 get_template_directory_uri() 方法获取 URL

<img src="<?php echo get_template_directory_uri(); ?>/path/to/logo/logo.png">

但是我怎样才能在媒体库中专门获取图片的替代文本呢?

【问题讨论】:

  • get_post_meta('你的图片ID在这里', '_wp_attachment_image_alt', true);
  • 谢谢。如何找到图像 ID?
  • 进入 wp-admin->media->required image->edit 它,在 url 中你会找到一个 post id,即你的 image id
  • 有没有办法在没有图像 id 的情况下获取图像替代文本?也许是图像名称?
  • 那你需要写一个自定义函数

标签: php html wordpress


【解决方案1】:

我已经写了一个函数来做到这一点。

将此函数添加到您的 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' );

【讨论】:

    猜你喜欢
    • 2014-01-06
    • 2015-12-29
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 2017-05-27
    相关资源
    最近更新 更多