自动将 Woocommerce 产品图片与产品标题匹配

Moh*_*has 1 php wordpress woocommerce

经过一些研究后,我发现图像标题和 alt 对于 SEO 非常重要,并且更改每个图像标题和 alt 会花费很长时间。

我在这里找到了这段代码,但它并不影响当前的图像。

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;
}
Run Code Online (Sandbox Code Playgroud)

Nil*_*bar 5

您可以尝试woocommerce_gallery_image_html_attachment_image_params过滤器进行自定义。检查以下示例。它获取产品标题并将其分配给图像的alt和属性。title注意:这仅适用于产品单页。

add_filter( 'woocommerce_gallery_image_html_attachment_image_params','wpso_customize_single_product_image' );

function wpso_customize_single_product_image( $details ) {
    global $product;
    $details['alt'] = $details['title'] = get_the_title( $product->get_id() );
    return $details;
}
Run Code Online (Sandbox Code Playgroud)