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

nvbavucw  于 2023-06-21  发布在  WordPress
关注(0)|答案(2)|浏览(171)

在做了一些研究后,我发现图像标题和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;
}
c86crjj0

c86crjj01#

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

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;
}
wj8zmpe1

wj8zmpe12#

登录到您的Phpmyadmin,选择您的数据库并运行此查询以更新图像标题:

UPDATE wp_posts as a
LEFT JOIN wp_postmeta as b ON a.ID = b.meta_value
LEFT JOIN wp_posts as c ON b.post_id = c.ID
SET a.post_title = c.post_title
WHERE a.post_type = 'attachment'
AND a.post_mime_type = 'image/jpeg'
AND b.meta_key = '_thumbnail_id'
AND c.post_type = 'product'

...和此SQL查询来更新图像alts:

UPDATE wp_postmeta as z 
LEFT JOIN wp_posts as a ON z.post_id = a.ID 
LEFT JOIN wp_postmeta as b ON a.ID = b.meta_value 
LEFT JOIN wp_posts as c ON b.post_id = c.ID 
SET z.meta_value = c.post_title 
WHERE z.meta_key = '_wp_attachment_image_alt' 
AND a.post_type = 'attachment' 
AND a.post_mime_type = 'image/jpeg' 
AND b.meta_key = '_thumbnail_id' 
AND c.post_type = 'product'

相关问题