Categories/javascript

From Freephile Wiki

JavaScript code like the following uses the internal MediaWiki Api to retrieve the categories and output a table with member page counts.

You can see the same info at Special:Categories - but this example gives you another way to slice and dice the information if desired.

mw.loader.using('mediawiki.api', function() {
    var api = new mw.Api();
    var $output = $('<div id="category-list"></div>');
    $output.append('<h2>Categories in this wiki</h2>');
    $output.append('<p>Loading categories...</p>');
    
    // Add to page
    $('#content').prepend($output);
    
    // Get all categories with their member counts
    api.get({
        action: 'query',
        list: 'allcategories',
        acprop: 'size', // Include the number of members in each category
        aclimit: 5000,  // Get up to 5000 categories (adjust as needed)
        format: 'json'
    }).done(function(data) {
        // Clear loading message
        $output.find('p').remove();
        
        if (!data.query || !data.query.allcategories || data.query.allcategories.length === 0) {
            $output.append('<p>No categories found.</p>');
            return;
        }
        
        // Categories are already sorted alphabetically in the API response
        var categories = data.query.allcategories;
        
        var $table = $('<table class="wikitable sortable"></table>');
        $table.append('<tr><th>Category</th><th>Pages</th></tr>');
        
        $.each(categories, function(i, cat) {
            var categoryName = cat['*'];
            var pageCount = cat.size;
            
            $table.append(
                '<tr>' +
                '<td><a href="/wiki/Category:' + encodeURIComponent(categoryName) + '">' + 
                categoryName + '</a></td>' +
                '<td>' + pageCount + '</td>' +
                '</tr>'
            );
        });
        
        $output.append($table);
        $output.append('<p>Total: ' + categories.length + ' categories</p>');
        
        // If your wiki has mw.loader.load('jquery.tablesorter') available
        if ($.tablesorter) {
            $table.tablesorter();
        }
    }).fail(function(error) {
        $output.find('p').text('Error fetching categories: ' + error);
    });
});