Jump to content

Module:CountWikidata

From Wikipedia, the free encyclopedia
--[[
Module : CountWikidata
Author : AdrianoRutz

Counts the number of statements for a given property for a given entity.

Use :
{{#invoke:CountWikidata|getClaimCount|entity=Q121802|property=P703}}
]]
local p = {}

function p.getClaimCount(frame)
    -- 1. Retrieve arguments
    -- We allow calling via frame args (direct #invoke)
    local args = frame.args

    -- 2. Clean and standardize inputs
    local property = args.property
    -- Accept 'entity', 'qid', or 'id' for flexibility
    local entityId = args.entity or args.qid or args.id

    -- If no property provided, we cannot count
    if not property then
        return 0
    end

    -- Ensure property is uppercase (e.g., "p703" -> "P703")
    property = string.upper(property)

    -- 3. Get the Entity
    -- mw.wikibase.getEntity() without args fetches the current page's item
    local entity
    if entityId and entityId ~= "" then
        entity = mw.wikibase.getEntity(entityId)
    else
        entity = mw.wikibase.getEntity()
    end

    -- 4. Validation
    -- If entity doesn't exist or has no claims, return 0
    if not entity or not entity.claims then
        return 0
    end

    -- 5. Count the claims
    local claims = entity.claims[property]

    if claims then
        return #claims
    else
        return 0
    end
end

return p