ssabin
ssabin

Reputation: 111

WooCommerce adding category banner to product page

I'm using WooCommerce and i want to show the product-category banner in product page. for the product-category i used this code:

add_action( 'woocommerce_archive_description', 'woocommerce_category_image', 2 );
function woocommerce_category_image() {
    if (is_product_category()){
        global $wp_query;
        $cat = $wp_query->get_queried_object();
        $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
        $image = wp_get_attachment_url( $thumbnail_id );
        if ( $image ) {
            echo '<img src="' . $image . '" alt="" class="cat_ban"/>';
        }
    }
}

and for the product page i use a similar code with some changes,but it doesn't work,can some one point me to my mistake?

add_action( 'woocommerce_archive_description', 'woocommerce_product_image', 2 );
function woocommerce_product_image() {
    if (is_product()){
        global $post;
        $terms = get_the_terms( $post->ID, 'product_cat' );
        $cat = $terms->term_id;
        $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
        $image = wp_get_attachment_url( $thumbnail_id );
        if ( $image ) {
            echo '<img src="' . $image . '" alt="" class="cat_ban"/>';
        }
    }
}

Upvotes: 1

Views: 1177

Answers (2)

Swapnali
Swapnali

Reputation: 1299

You can add category banner to product page use this code -

add_action('woocommerce_before_single_product', 'woocommerce_add_category_banner', 2);
function woocommerce_add_category_banner()
{
    global $product;
    if (isset($product) && is_product()) 
    {
        global $wp_query;
        $cat = $wp_query->get_queried_object();
        $thumbnail_id = get_woocommerce_term_meta($cat->term_id, 'thumbnail_id', true);
        $image = wp_get_attachment_url($thumbnail_id);
        if ($image) 
        {
            echo '<img src="' . esc_url($image) . '" alt="" />';
        }
    }
   }

Upvotes: 0

ssabin
ssabin

Reputation: 111

found a solution on my own,hope it will help you:

add_action( 'woocommerce_before_single_product', 'woocommerce_product_image', 2 );
function woocommerce_product_image(){

    $product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );

    if ( $product_cats && ! is_wp_error ( $product_cats ) ){

        $cat = array_shift( $product_cats ); 
        $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
        $image = wp_get_attachment_url( $thumbnail_id );
        $category_link = get_category_link($cat);
        if ( $image ) {
            echo '<a href="' .$category_link. '"><img src="' . $image . '" alt="" class="cat_ban"/></a>';
        }
    }
}

Upvotes: 1

Related Questions