我一直使用此代码将alt文本设置为与title相等,因为缺少alt文本。不过,在此之前,为了将文件名用作alt,我使用了$attr['alt'] = $attr['title'];。但是,它包含连字符,所以现在我正在尝试找到一种不同的方法来获取文件名。
我已经读到了很多关于如何检索文件名的建议,但到目前为止都没有起作用。还想删除文件扩展名。
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;
} 我如何才能做到这一点?
发布于 2021-07-30 14:34:18
假设您当前的代码可以工作(我还没有对其进行测试),您可以简单地将标题中的连字符替换为空格:
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;
}https://stackoverflow.com/questions/68591943
复制相似问题