Search code examples
wordpresswoocommercealt

WORDPRESS replace hyphens with space for $post->post_title


I am using this code in functions.php to set the "alt" text to equal the "title" as the alt text is missing.

The "title" is equal to the image filename which contains hyphens.

This works until i try to use str_replace('-', ' ', $string); to remove the hypens from "title" and subsequently "alt".

I am a complete coding novice which is why my attempts are not only not working but may be way off.

Is this possible to achieve?

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') {
    $title = $post->post_title;
    $replace = str_replace("-", " ", $title);
    $attr['alt'] = $attr['replace'];
    }
    return $attr;
} 

Solution

  • You almost got it!

    There's a small typo in your code here:

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

    Where it should be:

    $attr['alt'] = $replace;
    

    This is because $attr['replace'] doesn't exists and $replace is the variable that contains the changes you want to assign into $attr['alt']

    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') {
            $title = $post->post_title;
            $replace = str_replace("-", " ", $title);
            $attr['alt'] = $replace;
        }
        return $attr;
    }