Created
April 5, 2021 12:51
-
-
Save zainaali/5136e11f00a0f7dccfe2e1c047b5dba8 to your computer and use it in GitHub Desktop.
set alt tag and title of product images to product's name, category, subcategories' name, vendor's name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter( 'martfury_image_alt_text', 'ct_martfury_image_alt_text' ); | |
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2); | |
function change_attachement_image_attributes( $attr, $attachment ){ | |
$product_id = get_the_ID(); | |
$vendor_id = get_post_field( 'post_author', $product_id ); | |
// Get the WP_User object (the vendor) from author ID | |
$vendor = new WP_User($vendor_id); | |
$vendor_name = $vendor->display_name; | |
// var_dump($product_cat);exit; | |
// 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' ){ | |
// var_dump($type);exit; | |
return $attr; | |
} | |
$cat = get_the_terms( $product_id, 'product_cat' ); | |
$category_name = ''; | |
$category_id = ''; | |
foreach ($cat as $categoria) { | |
if($categoria->parent == 0){ | |
$category_name = $categoria->name; | |
$category_id = $categoria->term_id; | |
} | |
} | |
$child_terms = get_term_children($category_id, 'product_cat'); | |
$all_terms = wp_get_post_terms($product_id, 'product_cat'); | |
$child_cat = array(); | |
foreach ( $all_terms as $term ) { | |
$child_cat[] = $term->name; | |
} | |
/// Get title | |
$title = get_post_field( 'post_title', $parent); | |
$child_cat = implode(" - ",$child_cat); | |
// $child_cat = explode(" ",$child_cat); | |
// $child_cat = implode(" - ",$child_cat); | |
$attr['alt'] = $title.' - '.$category_name.' - '.$child_cat.' - '.$vendor_name; | |
$attr['title'] = $title.' - '.$category_name.' - '.$vendor_name; | |
return $attr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment