David
  • 0

How to add a new column in product list page (backend)?

  • 0

I want to add a new column for listing primary category in product list page (backend) of WooCommerce.

Also I want to fill the new column with primary category of each product.

1 Answer

  1. This answer was edited.

    You can create a new custom column in admin product list page. We can use manage_edit-product_columns filter hook and manage_product_posts_custom_column action hook for create new column.

    “Primary category” is not a default woocommerce feature. It is comes from yoast seo plugin. This field is stored in postmeta table with “_yoast_wpseo_primary_product_cat” meta_key.

    Add the following code in functions.php of your child theme.

    // ==== add primary category column to products list page ====
    add_filter('manage_edit-product_columns', 'wp_wiki_add_primary_category_column', 10);
    function wp_wiki_add_primary_category_column($columns)
    {
        $new_columns = array();
        foreach ($columns as $column_name => $column_info) {
            $new_columns[$column_name] = $column_info;
            if ('product_cat' === $column_name) {
                // Add New column after category column
                $new_columns['primary_cat'] = __('Primary Category', 'my_textdomain');
            }
        }
        return $new_columns;
    }
    
    // ==== add primary category column content to new column ====
    add_action('manage_product_posts_custom_column', 'wp_wiki_add_primary_category_column_content');
    function wp_wiki_add_primary_category_column_content($column)
    {
        global $post;
        if ('primary_cat' === $column) :
            $taxonomy = 'product_cat';
            $primary_cat_id = get_post_meta($post->ID, '_yoast_wpseo_primary_product_cat', true);
            $primary_cat_name = '';
            if ($primary_cat_id) :
                $primary_cat = get_term($primary_cat_id, $taxonomy);
                if (isset($primary_cat->name)) :
                    $primary_cat_name = $primary_cat->name;
                endif;
            endif;
            echo $primary_cat_name;
        endif;
    }
    

    This will create a new column with “Primary Category” as shown in the below screenshot.

Leave an answer

You must login to add an answer.