首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WORDPRESS获取要用作ALT的文件名

WORDPRESS获取要用作ALT的文件名
EN

Stack Overflow用户
提问于 2021-07-30 13:41:56
回答 1查看 45关注 0票数 0

我一直使用此代码将alt文本设置为与title相等,因为缺少alt文本。不过,在此之前,为了将文件名用作alt,我使用了$attr['alt'] = $attr['title'];。但是,它包含连字符,所以现在我正在尝试找到一种不同的方法来获取文件名。

我已经读到了很多关于如何检索文件名的建议,但到目前为止都没有起作用。还想删除文件扩展名。

代码语言:javascript
复制
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes($attr, $attachment) {
global $post;
$product = wc_get_product( $post->ID );
if ($post->post_type == 'product') {
    $image_id = get_post_thumbnail_id();
    $image_filename = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
    $attr['alt'] = basename($image_filename);
    }
    return $attr;
}  

我如何才能做到这一点?

EN

回答 1

Stack Overflow用户

发布于 2021-07-30 14:34:18

假设您当前的代码可以工作(我还没有对其进行测试),您可以简单地将标题中的连字符替换为空格:

代码语言:javascript
复制
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes($attr, $attachment) {
global $post;
$product = wc_get_product( $post->ID );
if ($post->post_type == 'product') {
    $image_id = get_post_thumbnail_id();
    $image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
    $attr['alt'] = str_replace("-", " ", $attr['title']);
    }
    return $attr;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68591943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档