【问题标题】:How can I let woocommerce set products' title as the product image's title and alt?如何让 woocommerce 将产品标题设置为产品图片的标题和 alt?
【发布时间】:2022-03-19 04:15:26
【问题描述】:

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

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    您可以尝试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;
    }
    

    【讨论】:

      【解决方案2】:

      登录到您的 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'
      

      ...以及用于更新图像 alts 的 SQL 查询:

      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'
      

      【讨论】:

      • 我应用了这些代码,有几行受到影响,但前端没有任何变化
      • @MohammadAlnahhas 您应该清除瞬态以在前端进行更改。运行这些查询:DELETE FROM wp_options WHERE option_name LIKE ('%\_transient\_%')DELETE FROM wp_options WHERE option_name LIKE ('%\_site_transient_\_%')
      • 我不知道为什么这对我不起作用,这是我的网站 siphers.store
      • @MohammadAlnah 已查看此产品的缩略图:siphers.store/product/xbox-live-gold-3-month,Alt 已更改,但标题未更改。也许您的主题正在覆盖 WooCommerce 模板文件。转到您的主题文件夹,在woocommerce 的子文件夹中找到product-image.php 文件。
      • 我应该如何处理那个文件?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 2018-10-21
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多