Add Product Attributes Column

Adds a custom "Attributes" column to the WooCommerce product table.

PHP
/**
 * Snippet Name:     Add Product Attributes Column
 * Snippet Author:   coding-bunny.com
 * Description:      Adds a custom "Attributes" column to the WooCommerce product table.
 */
 
// Add a custom column to the WooCommerce product table
function cb_add_attributes_column($columns) {
    $columns['cb_attributi'] = 'Attributes'; // Add "Attributes" column
    return $columns;
}
add_filter('manage_edit-product_columns', 'cb_add_attributes_column');

// Populate the custom "Attributes" column with data
function cb_populate_attributes_column($column, $post_id) {
    if ($column == 'cb_attributes') {
        $product = wc_get_product($post_id); // Get the product object
        
        if (!$product) {
            echo esc_html('-'); // Display a placeholder if the product is invalid
            return;
        }

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

        if (!empty($attributes)) {
            foreach ($attributes as $attribute) {
                $attribute_name = wc_attribute_label($attribute->get_name()); // Get attribute label

                // Check if the attribute is taxonomy-based or custom
                if ($attribute->is_taxonomy()) {
                    // Get taxonomy terms associated with the attribute
                    $attribute_values = wc_get_product_terms($post_id, $attribute->get_name(), array('fields' => 'names'));
                    $attribute_options = implode(', ', array_map('esc_html', $attribute_values)); // Sanitize and implode terms
                } else {
                    // Get custom attribute options
                    $attribute_options = implode(', ', array_map('esc_html', $attribute->get_options())); // Sanitize options
                }

                // Output attribute name and values
                echo '<p><strong>' . esc_html($attribute_name) . ':</strong> ' . $attribute_options . '</p>';
            }
        } else {
            echo esc_html('-'); // Display a placeholder if no attributes exist
        }
    }
}
add_action('manage_product_posts_custom_column', 'cb_populate_attributes_column', 10, 2);

How To Implement This Solution?

Leave a Reply

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

My Agile Privacy
This site uses technical and profiling cookies. You can accept, decline or customize cookies by pressing the desired buttons. By closing this policy you will continue without accepting.

Need help?

Choose one of the following options:

Powered by CodingBunny