woocommerceproduct

How to display some attributes directly on shop page/product page in WooCommerce?


I'm trying to display some attributes directly on the shop page. The attributes are all collected in the database. To make it easier to show, I made a screenshot so you can get a better idea. the thing is now, with which code I can do that. the attributes, there are always 4, should be display centered under the block with the pictures and the buy button. I would be very happy if we could find a way to do this. Thanks very much

enter image description here

Ok, i've found some code here on stackoverflow... the good news are, i get the results/attributes i want, the bad news are, on the wrong page (shop page instead of shop page single).

this is the code:

add_action('woocommerce_after_shop_loop_item_title', 'display_custom_product_attributes_on_loop', 5 );
function display_custom_product_attributes_on_loop() {
    global $product;

    // Settings: Here below set your product attribute label names
    $attributes_names = array('alter', 'bausteine', 'publicationdate', 'sku');

    $attributes_data  = array(); // Initializing

    // Loop through product attribute settings array
    foreach ( $attributes_names as $attribute_name ) {
        if ( $value = $product->get_attribute($attribute_name) ) {
            $attributes_data[] = $attribute_name . ': ' . $value;
        }
    }

    if ( ! empty($attributes_data) ) {
        echo '<div class="items" style="color: red;"><p>' . implode( '<br>', $attributes_data ) . '</p></div>';
    }
}

this code shows me the attributes and the results on the shoppage, but i need it on the single shop page/product page.

Thank you!


Solution

  • Change the hook name and then check

    add_action('woocommerce_single_product_summary', 'display_custom_product_attributes_on_loop', 5 );
    
    function display_custom_product_attributes_on_loop() {
        global $product;
    
        // Settings: Here below set your product attribute label names
        $attributes_names = array('alter', 'bausteine', 'publicationdate', 'sku');
    
        $attributes_data  = array(); // Initializing
    
        // Loop through product attribute settings array
        foreach ( $attributes_names as $attribute_name ) {
            if ( $value = $product->get_attribute($attribute_name) ) {
                $attributes_data[] = $attribute_name . ': ' . $value;
            }
        }
    
        if ( ! empty($attributes_data) ) {
            echo '<div class="items" style="color: red;"><p>' . implode( '<br>', $attributes_data ) . '</p></div>';
        }
    }