InCategory

Summary: Custom conditional markup to determine if a page is in a category
Version: 20220606
Prerequisites: PmWiki 2.3.1+
Status: Experimental
Maintainer: Petko
License: GPL
Categories: Links, Markup, PHP81
Users: +1 (view / edit)
Discussion: InCategory-Talk?

Questions answered by this recipe

I want to use conditional markup to determine if a page has been tagged with a specific category. Any idea if I can achieve this?

Description

Custom conditional markup to determine if a page is in a category.

This only works with the 2.3.x categories, where the pages use the [[!Category]] markup. If your wiki used categories in the past, and upgraded from an earlier PmWiki version, you need to also reindex categories.

Installation

Add this to local configuration:

  $FmtPV['$Targets'] = '$page["targets"]';
  $Conditions['incategory'] = 'CondInCategory($pagename, $condparm)';
  function CondInCategory($pagename, $condparm) {
    list($cat, $pn) = preg_split('/\\s+/', $condparm, -1, PREG_SPLIT_NO_EMPTY);
    if(! $pn) $pn = $pagename;
    else $pn = MakePageName($pagename, $pn);
    preg_match_all('/!([^.,]+)/', PageVar($pn, '$Targets'), $m);
    $list = MatchNames($m[1], $cat);  
    return count($list);
  }

Usage

In a wiki page, use the markup (:if incategory CategorySpec Page:):

(:if incategory Images,Uploads Cookbook.Mini:)
* Page [[Cookbook.Mini]] is in at least one category among "Images" and "Uploads"
(:else:)
* Page [[Cookbook.Mini]] is neither in "Images" nor in "Uploads".
(:ifend:)
  • Page Cookbook.Mini is in at least one category among "Images" and "Uploads"

The recipe is enabled on this page, feel free to test it in the Sandbox section.

The category specification may have different categories, separated by commas, and wildcards.

The page name is optional; if not provided, the currently browsed page is assumed (may be useful in headers, footers, sidebars).

Notes

  • Unlike the name of the recipe, the conditional is lowercase.
  • Multiple "page" specifications as Page1,Page2 are not supported.
  • Negations for the category specifications, as in "-Category1" are not supported.

Change log / Release notes

  • 20220606 First public release, ready to be tested.

See also

Cookbook /
ConditionalMarkupSamples  List of default and custom conditional markup definitions (Stable)
ReindexCategories  Update link targets and page index for PmWiki 2.3.0 (beta)

Contributors

  • Written and maintained by Petko.

Comments

See discussion at InCategory-Talk?

Sandbox

Feel free to test the recipe here.

User notes +1: If you use, used or reviewed this recipe, you can add your name. These statistics appear in the Cookbook listings and will help newcomers browsing through the wiki.