Add a submenu page to the WooCommerce “Products” menu

/**
 * Adds "Best Sellers" submenu page to the WooCommerce "Products" menu.
 *
 * @see https://wpcodebook.com/add-submenu-page-woocommerce-products-menu/
 * @see https://developer.wordpress.org/reference/functions/add_submenu_page/
 * @see https://developer.wordpress.org/reference/hooks/admin_menu/
 */
add_action( 'admin_menu', function () {
	add_submenu_page(
		'edit.php?post_type=product',
		esc_html__( 'Best Sellers' ),
		esc_html__( 'Best Sellers' ),
		'manage_woocommerce',
		'wpcodebook-best-sellers',
		function () {
			$rows = '';
			$args = array(
				'limit'    => 10,
				'orderby'  => 'meta_value_num',
				'meta_key' => 'total_sales',
				'order'    => 'DESC',
			);
			foreach ( wc_get_products( $args ) as $product ) {
				$rows .= sprintf( '<tr><th>%s</th><td>%s</td></tr>',
					$product->get_name(), $product->get_total_sales() );
			}
			echo '<div class="wrap">' .
				'<h1>' . esc_html__( 'Top 10 Best Sellers' ) . '</h1>' .
				'<table class="widefat striped">' .
					$rows .
				'</table>' .
			'</div>';
		}
	);
} );

Leave a Comment