atsngr
atsngr

Reputation: 181

Woocommerce product top category and subcategories images with ACF

I am using Woocommerce along with ACF. I needed an image to be displayed as category image for each product category. I got that well with the code below after going through your community forum.

<?php 
    if ( is_product_category() ) {
        // vars
        $queried_object = get_queried_object(); 
        $taxonomy = $queried_object->taxonomy;
        $term_id = $queried_object->term_id; 
    }

    $custom_cat_title = get_field('page_header_image', $taxonomy . '_' . $term_id);
?>

<?php if ($custom_cat_title): ?>

    <div class="page-title bwp-title custom-bg-cover" style="background-image:url(<?php echo $custom_cat_title; ?>);">
        <div class="container" >
            <div class="titlewrapper" >
                <?php if(!is_single() ) :  ?>
                    <h1>
                        <?php echo single_cat_title(); ?>
                    </h1>
                <?php endif; ?>
            </div><!-- .titlewrapper -->    
        </div><!-- .container -->

    </div><!-- Page Title -->   

<?php endif; ?>

There is still one more thing I need which I cannot figure out yet. That is to have the image uploaded for a parent category to be used automatically for its subcategories - if those subcategories do not have their own image uploaded.

I am not an expert in PHP but I can follow instruction and examples if I see one. Can you please point me in a direction I can go?

Thanks

Upvotes: 0

Views: 390

Answers (1)

Wilco
Wilco

Reputation: 383

I think you're looking for this

<?php
    if ( is_product_category() ) {
        // vars
        $queried_object = get_queried_object();
        $taxonomy = $queried_object->taxonomy;
        $term_id = $queried_object->term_id;
    }

    // Image
    $custom_cat_title = get_field('page_header_image', $taxonomy . '_' . $term_id);

    if( empty( $custom_cat_title ) ) {

        $parent = $queried_object->parent;

        // Parent image
        $custom_cat_title = get_field( 'page_header_image', $taxonomy . '_' . $parent );
    }

?>

<?php if ($custom_cat_title): ?>

    <div class="page-title bwp-title custom-bg-cover" style="background-image:url(<?php echo $custom_cat_title; ?>);">
        <div class="container" >
            <div class="titlewrapper" >
                <?php if(!is_single() ) :  ?>
                    <h1>
                        <?php echo single_cat_title(); ?>
                    </h1>
                <?php endif; ?>
            </div><!-- .titlewrapper -->
        </div><!-- .container -->

    </div><!-- Page Title -->

<?php endif; ?>

This will look for the current term image. If it doesn't have an image it will look for the image from the parent term.

Upvotes: 1

Related Questions