0
votes

I'm currently building a theme using Understrap. I want to add images to attributes. Right now, i'm using the following plugin : Advanced Category and Custom Taxonomy Image but i can't figure out how to display my images along with their text in my single-product page.

Right now, i've done the following :

/**
 * Add a custom product data tab
 */
add_filter('woocommerce_product_tabs', 'woo_new_product_tab');
function woo_new_product_tab($tabs)
{

    // Adds the new tab

    $tabs['test_tab'] = array(
        'title'     => __('Ingredients', 'woocommerce'),
        'priority'  => 50,
        'callback'  => 'woo_new_product_tab_content'
    );

    return $tabs;
}
/**
 * Remove product data tabs
 */
add_filter('woocommerce_product_tabs', 'woo_remove_product_tabs', 98);

function woo_remove_product_tabs($tabs)
{
    unset($tabs['additional_information']);   // Remove the additional information tab
    return $tabs;
}
function woo_new_product_tab_content()
{
    echo '<h2>Ingredients</h2>';
    // echo '<p>Here\'s your new product tab.</p>';
    global $product;
    $attributes = $product->get_attribute('ingredients');

    foreach ($attributes as $attribute) {
        $terms = wp_get_post_terms($product->get_id(), $attribute['name']);

        foreach ($terms as $term) {
            $taxonomy_img = get_taxonomy_image($term->term_id);
        }
    }

    print  $attributes;
}

But it only displays the text and not the images. What am i missing ?

1

1 Answers

1
votes

There are some errors in the woo_new_product_tab_content() function.

The get_attribute() method returns a comma separated value string.
So it can't be used as an argument for foreach, you need to convert it to array first.

Furthermore, the value of the foreach will already be the slug of the term of the attribute.

Try with this:

function woo_new_product_tab_content() {
    echo '<h2>Ingredients</h2>';
    global $product;
    // the taxonomy of a product attribute is always preceded by "pa_"
    $attribute_taxonomy = 'pa_ingredients';
    $attributes = $product->get_attribute( $attribute_taxonomy );
    // convert string to array
    $attribute_slugs = explode( ',', $attributes );
    // for each product attribute value
    foreach ( $attribute_slugs as $attribute ) {
        // gets term id based on term slug
        $term_id = get_term_by( 'slug', $attribute, $attribute_taxonomy )->term_id;
        echo get_taxonomy_image( $term_id );
    }
}

I haven't tested it but it should work.