On IRC chat yesterday, Ryan Lane gave me some advice regarding my attempt to write an extension that would append some wikitext to articles prior to parsing. As he and a couple of other people suggested, the hook that I was trying to use for this purpose -- ArticleAfterFetchContent -- didn't work as hoped because of some caching issues. However, I have been able to get something working using the ParserBeforeStrip hook. Since Ryan said that he was interested in knowing how to do this for something he was trying to do, I thought I should document my technique here.
Here's a simplified version of the code I settled on:
<?php $wgHooks['ParserBeforeStrip'][] = 'wfMyTextAppend';
function wfMyTextAppend(&$parser, &$text, &$strip_state) { global $wgMyTextAppendFlag, $wgRequest; if (!$wgMyTextAppendFlag && $parser->getTitle()->getNamespace() == NS_MAIN) { $action = $wgRequest->getVal( 'action', 'view' ); if (empty( $action ) || $action == 'submit' || $action == 'view' || $action == 'purge') { $text .= "\nThis article is titled '''" . $parser->getTitle()-
getText() . "'''";
} $wgMyTextAppendFlag = true; } } ?>
Explanation:
(1) I created the $wgMyTextAppendFlag global because other extensions (such as the GIS/Wiki RSS extension) invoke the parser separately from the parsing of the entire page, in order to parse their input. Since my hook will be triggered at the beginning of parsing the wikitext for the entire page, I use the $wgMyTextAppendFlag as a way of signalling subsequent invocations of the parser that the wfMyTextAppend function has already run, thus ensuring that my text will only be appended at the end of the entire article and not elsewhere.
(2) The test $parser->getTitle()->getNamespace() == NS_MAIN ensures that my text only gets appended on articles in the main namespace and not on Special pages, Talk pages, etc.
(3) I use $wgRequest to test what kind of action is being performed, thus ensuring that my text is not appended when action=edit or some other unwanted context.
(4) The line that begins "$text .=" appends wikitext that produces a phrase followed by the name of the article in bold. This, of course, is pointless. In my actual extension, I did some further munging to get wikitext that displays results of an RSS feed which pulls in a search result based on the article title.
-------------------------------- | Sheldon Rampton | Research director, Center for Media & Democracy (www.prwatch.org) | Author of books including: | Friends In Deed: The Story of US-Nicaragua Sister Cities | Toxic Sludge Is Good For You | Mad Cow USA | Trust Us, We're Experts | Weapons of Mass Deception | Banana Republicans | The Best War Ever -------------------------------- | Subscribe to our free weekly list serve by visiting: | http://www.prwatch.org/cmd/subscribe_sotd.html | | Donate now to support independent, public interest reporting: | https://secure.groundspring.org/dn/index.php?id=1118 --------------------------------