Jump to content

Module:Article link count

From Wikipedia, the free encyclopedia

-- Article link count module
-- Initial code by Stefen 𝕋ower nĂ© Steve Magruder (5 March 2026) [[User:StefenTower]].
-- @module Article link count
local p = {}

function p.countUniqueArticleLinks(frame)
    local args = frame.args
    if args[1] == nil and args.page == nil then
        args = frame:getParent().args
    end
    
    local pageName = args[1] or args.page or ""
    if pageName == "" then return "0" end

    local targetTitle = mw.title.new(pageName)
    if not targetTitle or not targetTitle.exists then
        return "0" -- Returns 0 if the page doesn't exist
    end

    local text = targetTitle:getContent()
    
    -- Disregard links within html comments or nowiki tags
    text = text:gsub("<!%-%-.-%-%->", "")
    text = text:gsub("<[Nn][Oo][Ww][Ii][Kk][Ii]>.-</[Nn][Oo][Ww][Ii][Kk][Ii]>", "")
    
    local uniqueLinks = {}
    local count = 0

    for linkText in text:gmatch("%[%[([^%[%]|]+)") do
        linkText = mw.text.trim(linkText)
        
        if linkText ~= "" and not uniqueLinks[linkText] then
            local linkTitle = mw.title.new(linkText)
            if linkTitle and linkTitle.namespace == 0 then
                uniqueLinks[linkText] = true
                count = count + 1
            end
        end
    end

    return count
end

return p