I'm trying to add the product title and some taxonomy terms to the image alt and image title text on the front end. I can add the product title with the function below but I'd like to append the taxonomy terms from the default woocommerce product_cat and also some custom taxonomies outlined below:
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);
// Bail if it's not a product or if admin
$type = get_post_field( 'post_type', $parent);
if( is_admin() || $type != 'product' ){
return $attr;
}
// Get title
$title = get_post_field( 'post_title', $parent);
// Get Product Category
$product_cat = get_the_terms($post->ID,'product_cat');
// Get Artwork Category
$artwork_cat = get_the_terms($post->ID,'artwork-category');
// Get Artwork Materials
$artwork_material = get_the_terms($post->ID,'artwork-materials');
$attr['alt'] = $title;
$attr['title'] = $title;
return $attr;
}
Ideally, I'd like to output something like:
"$title, a $artwork_cat by $product_cat. $artwork_material" (E.g. The Mona Lisa, a painting by Leonardo Da Vinci. Oil on board.)
Any help would be great!
CodePudding user response:
You have to pass the product id to the get_the_terms
function which is you already getting in $parent
. Try the below code.
function change_attachement_image_attributes( $attr, $attachment ){
// Get post parent
$parent = get_post_field( 'post_parent', $attachment);
// Bail if it's not a product or if admin
$type = get_post_field( 'post_type', $parent);
if( is_admin() || $type != 'product' ){
return $attr;
}
// Get title
$title = get_post_field( 'post_title', $parent);
// Get Product Category
$product_cat = get_the_terms($parent,'product_cat');
// Get Artwork Category
$artwork_cat = get_the_terms($parent,'artwork-category');
// Get Artwork Materials
$artwork_material = get_the_terms($parent,'artwork-materials');
$title = $title.', a'.$artwork_cat.' by '.$product_cat[0]->name.'. '.$artwork_material.'.';
$attr['alt'] = $title;
$attr['title'] = $title;
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2 );