User:TweetsFactsAndQueries/Queries/Commons categories

Commons categories of items, taken from the Commons category (P373) category if it exists and otherwise from the commonswiki sitelink if it’s in the Category namespace. This is useless on its own, but can be used as part of a larger query. It must be used as a named subquery, because the optimizer has to be disabled for the sitelink fallback to work properly.

WITH {
  # their categories (via P373 or commonswiki sitelink, which gets a bit complicated)
  SELECT ?item ?commonsCategory WHERE {
    hint:SubQuery hint:optimizer "None". # we have to disable the optimizer for this subquery because it gets confused by the ?commonsCategoryStatementEn part
    INCLUDE %items.
    OPTIONAL {
      ?item wdt:P373 ?commonsCategoryStatement.
      BIND(STRLANG(CONCAT("Category:", ?commonsCategoryStatement), "en") AS ?commonsCategoryStatementEn)
      ?commonsCategoryFromStatement schema:name ?commonsCategoryStatementEn;
                                    schema:isPartOf <https://commons.wikimedia.org/>.
    }
    OPTIONAL {
      ?commonsCategoryFromSitelink schema:about ?item;
                                   schema:isPartOf <https://commons.wikimedia.org/>.
      FILTER(STRSTARTS(STR(?commonsCategoryFromSitelink), "https://commons.wikimedia.org/wiki/Category:"))
    }
    BIND(COALESCE(?commonsCategoryFromStatement, ?commonsCategoryFromSitelink) AS ?commonsCategory)
    FILTER(BOUND(?commonsCategory))
  }
} AS %itemsWithCommonsCategories
Try it!

Originally extracted from User:TweetsFactsAndQueries/Queries/UK Members of Parliament whose Commons categories are not yet in Category:Politicians of the United Kingdom.

Use in other query pages with the following wikitext inside the query:

{{User:TweetsFactsAndQueries/Queries/Commons categories|style=query}}