Use a shortcode to add a custom product attribute.

PHP Code Snippets/Functions

Insert this code into functions.php

function custom_product_attributes_shortcode() {
    ob_start();
    global $product;
    // Check if we're on a single product page
    if ( is_product() ) {
        echo '<div class="product-specs selected-attributes-info">';

        // Get the product attributes
        $attributes = $product->get_attributes();
        $attribute_count = count( $attributes );

        if ( $attribute_count === 0 || $attribute_count <= 2 ) {
            echo '<p>Not Specified</p>';
        } else {
            foreach ( $attributes as $attribute ) {
                $attribute_name = $attribute->get_name();
                $attribute_label = wc_attribute_label( $attribute_name );
                $selected_value = $product->get_attribute( $attribute_name );

                // Exclude certain classes
                $exclude_classes = array( 'pa_color', 'pa_variant' );
                $class_name = sanitize_title( $attribute_name );

                if ( $selected_value && ! in_array( $class_name, $exclude_classes ) ) {
                    echo '<div class="spec ' . esc_attr( $class_name ) . '">';
                    echo '<p class="spec-name">' . esc_html( $attribute_label ) . '</p>';
                    echo '<p class="spec-details">' . esc_html( $selected_value ) . '</p>';
                    echo '</div>';
                }
            }

            // Check if ACF field 'technical_specification' exists
            if ( have_rows( 'technical_specification', $product->get_id() ) ) {
                while ( have_rows( 'technical_specification', $product->get_id() ) ) {
                    the_row();
                    // Get sub field values.
                    $term_other_descriptions = get_sub_field( 'other_descriptions' );

                    if ( $term_other_descriptions ) {
                        echo '<div class="spec other_description">';
                        echo '<p class="spec-name">Other Descriptions</p>';
                        echo '<p class="spec-details">' . esc_html( $term_other_descriptions ) . '</p>';
                        echo '</div>';
                    }
                }
            }
        }

        echo '</div>';
    }

    return ob_get_clean();
}
add_shortcode( 'custom_product_attributes', 'custom_product_attributes_shortcode' );

Leave a Reply

Your email address will not be published. Required fields are marked *