我如何更改目录缩略图、产品缩略图中的元(alt 和标题)? - 伍科商贸

问题描述 投票:0回答:2

默认情况下,

Woocommerce
中的替代项使用图像文件的名称。

有谁知道如何更改缩略图元(alt 和标题)以显示产品名称

php wordpress image woocommerce
2个回答
8
投票

试试这个:

add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);

function change_attachement_image_attributes( $attr, $attachment ){
    // Get post parent
    $parent = get_post_field( 'post_parent', $attachment);

    // Get post type to check if it's product
    $type = get_post_field( 'post_type', $parent);
    if( $type != 'product' ){
        return $attr;
    }

    /// Get title
    $title = get_post_field( 'post_title', $parent);

    $attr['alt'] = $title;
    $attr['title'] = $title;

    return $attr;
}

5
投票

我已将 XciD 的答案更新为更简洁的版本:

add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes($attr, $attachment) {
    global $post;
    if ($post->post_type == 'product') {
        $title = $post->post_title;
        $attr['alt'] = $title;
        $attr['title'] = $title;
    }
    return $attr;
}   

不幸的是,在主图像上,该脚本对我不起作用(XciD 也一样),但在小拇指上却是这样。有趣:)

更新:如果我关闭主图像,则脚本将从第二个拇指开始工作!

更新2:好的。这是一句“天啊,请不要!”一些坏话JS代码改变了alt标签。天哪...

© www.soinside.com 2019 - 2024. All rights reserved.