Created
December 15, 2023 11:16
-
-
Save hslaszlo/49e50811558ecc95a218dd5698c8eb35 to your computer and use it in GitHub Desktop.
Adding an attributes column to WooCommerce admin products list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function add_product_column( $columns ) { | |
//add column | |
$columns['new_column'] = __( 'New column', 'woocommerce' ); | |
return $columns; | |
} | |
add_filter( 'manage_edit-product_columns', 'add_product_column', 10, 1 ); | |
function add_product_column_content( $column, $postid ) { | |
if ( $column == 'new_column' ) { | |
// output variable | |
$output = ''; | |
// Get product object | |
$product = wc_get_product( $postid ); | |
// Get Product Variations - WC_Product_Attribute Object | |
$product_attributes = $product->get_attributes(); | |
// Not empty, contains values | |
if ( !empty( $product_attributes ) ) { | |
foreach ( $product_attributes as $product_attribute ) { | |
// Get name | |
$attribute_name = str_replace( 'pa_', '', $product_attribute->get_name() ); | |
// Concatenate | |
$output = $attribute_name . ' = '; | |
// Get options | |
$attribute_options = $product_attribute->get_options(); | |
// Not empty, contains values | |
if ( !empty( $attribute_options ) ) { | |
foreach ($attribute_options as $key => $attribute_option ) { | |
// WP_Term Object | |
$term = get_term($attribute_option); // <-- your term ID | |
// Not empty, contains values | |
if ( !empty( $term ) ) { | |
$term_name = $term->name; | |
// Not empty | |
if ( $term_name != '' ) { | |
// Last loop | |
end($attribute_options); | |
if ( $key === key($attribute_options) ) { | |
// Concatenate | |
$output .= $term_name; | |
} else { | |
// Concatenate | |
$output .= $term_name . ', '; | |
} | |
} | |
} | |
} | |
} | |
echo $output . '<br>'; | |
} | |
} | |
} | |
} | |
add_action( 'manage_product_posts_custom_column', 'add_product_column_content', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment