If you have to extend the backend product grid of Woocommerce by an custom attribute , you have to follow the steps below to add product attribute columns to Woocommerce backend grid:
- Register and sort  the new columns via a filter hook (‘manage_edit-product_columns’):
<?php add_filter( 'manage_edit-product_columns', 'add_columns_to_product_grid', 10, 1 ); const BACKEND_PRODUCT_GRID_FIELD_SORTORDER = [ 'cb', 'thumb', 'name', 'pa_size_text', 'sku', 'is_in_stock', 'price', 'product_cat', 'product_tag', 'featured', 'product_type', 'date', 'stats', 'likes' ]; /** * Registers new columns for the backend products grid of Woocommerce. * Additionally it sorts the fields after * self::BACKEND_PRODUCT_GRID_FIELD_SORTORDER. Fields not included in * self::BACKEND_PRODUCT_GRID_FIELD_SORTORDER will be attached to the end of * the array. * * @param array $aColumns - the current Woocommerce backend grid columns * * @return array - the extended backend grid columns array */ public function add_columns_to_product_grid( $aColumns ) { $aColumns['pa_size_text'] = __( 'Unit size', 'sheldon_misc' ); #unset($aColumns['thumb']); $aReturn = []; foreach ( self::BACKEND_PRODUCT_GRID_FIELD_SORTORDER as $sKey ) { if ( isset( $aColumns[ $sKey ] ) ) { $aReturn[ $sKey ] = $aColumns[ $sKey ]; } } /** * search additional unknown fields and attache them to the end */ foreach ( $aColumns as $sKey => $sField ) { if ( ! isset( $aReturn[ $sKey ] ) ) { $aReturn[ $sKey ] = $sField; } } return $aReturn; }
- Add an action hook to fill in the respective value of each row (‘manage_product_posts_custom_column’):
<?php add_action( 'manage_product_posts_custom_column', 'add_columns_value_to_product_grid', 10, 2 ); /** * Adds the respective value of the custom attribute to each row of the * column * * @param string $sAttributeCode * @param int $iPostId */ public function add_columns_value_to_product_grid( $sAttributeCode, $iPostId ) { if ( $sAttributeCode == 'pa_size_text' ) { $oProduct = new WC_Product( $iPostId ); $sSizeText = $oProduct->get_attribute( 'pa_size_text' ); echo esc_attr( $sSizeText ); } }
For simplicity I only show the raw functions here. In general it is a really good Idea to encapsulate the code into a plugin class! 😉
Further information on how to add product attribute columns to Woocommerce backend grid
For this short article I was inspired by this Stack Overflow question:
This does not work, you cannot just put in the class stuff in the source without framing.
Hi,
Indeed it worked for me that way. How would you do it instead? Can you give me an example please?
Kind regards,
Sheldon
You have ‘public’ before your functions, which should be used in class methods. I’m sure that’s what he’s referring to.
Ah OK. Yes that could be. I think, the reason why this is working anyway is, that “public” is the default scope. What I can say for sure is, that it works for at least one of my stores like that.
hi,
Is it possible to make it sortable ?