0
votes

I'm new in Woocommerce. I would like to customize the template for the product page of Woocommerce just for the books category. I replaced the content-single-product.php file with a custom one modifying the code in single-product.php file like this:

 <?php while ( have_posts() ) : the_post(); ?>
    <?php 
                global $post;
                $terms = wp_get_post_terms( $post->ID, 'product_cat' );
                foreach ( $terms as $term ) $categories[] = $term->slug;
                if ( in_array( 'livros', $categories ) ) {
                    wc_get_template_part( 'content', 'single-product-books' );              
                } else {
                    wc_get_template_part( 'content', 'single-product' );                
                }
                ?>
    <?php endwhile; // end of the loop. ?>

Now I want to do the same in replacing the product-image.php file with this one product-image-books.php. Tried like this but not working:

global $post;
            $terms = wp_get_post_terms( $post->ID, 'product_cat' );
            foreach ( $terms as $term ) $categories[] = $term->slug;
            if ( in_array( 'books', $categories ) ) {
                wc_get_template_part( 'content', 'single-product-books' );
                wc_get_template_part( 'single-product/product', 'image-books' );
            } else {
                wc_get_template_part( 'content', 'single-product' );
                wc_get_template_part( 'content', 'product-image' );
            }
            ?>

This file is in the template folder: woocommerce > single-product. Any help?

1

1 Answers

3
votes

The single product images are displayed using woocommerce_show_product_images() function & hooked via woocommerce_before_single_product_summary hook.

So instead of calling template directly, first remove the action from that hook and then add your custom function on the same hook.

Your files to show images (product-image-books.php & product-image.php) must be with in wordpress\wp-content\themes\your-theme\woocommerce\single-product\ directory.

Please add below code in your theme's functions.php file or custom plugin file. I have tested the code & it's working fine in my installation.

remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );

add_action( 'woocommerce_before_single_product_summary', 'qt563_woocommerce_show_product_images', 20 );

function qt563_woocommerce_show_product_images() {
    global $post;
    $terms = wp_get_post_terms( $post->ID, 'product_cat' );
    foreach ( $terms as $term ) $categories[] = $term->slug;
    if ( in_array( 'livros', $categories ) ) {
        wc_get_template( 'single-product/product-image-books.php' );              
    } else {
        wc_get_template( 'single-product/product-image.php' );                
    }
}

@Emmanu, Can you please verify & accept it as answer?