Output-Buffering and Extensible WordPress Plug-Ins

Contrary to my tentative conclusions of a month ago, I now understand at least one good reason to use output-buffering while writing WordPress code. Indeed, I now anticipate using the tool frequently.

While asking a question to developers at StackOverflow, I wrote the following:

My general impression is that, unless I have a very good reason for using it – probably involving the kind of script in which I’m not generally interested at this time – I should avoid it. Yet I’ll read suggestions that I could use buffering in one or another normal context (e.g., a shortcode that renders a large block of HTML), and I often see it being used in code by people whose work I admire and try to emulate. I’ve seen the familiar ob_start() etc. sequences applied for rendering even very minimal output that is not further adjusted: a menu or other short list, for example.

I have also seen people assert that there is simply no need for output buffering in well-written code, except in peculiar situations… Others will say it’s useful ONLY when some manipulation of the output is necessary – like a preg_replace of content – but you don’t need an output buffer to do that kind of thing (any ol’ variable will do).

The minimal response I received tended toward agreement: “I have no idea,” said one developer, “why some people would forcedly output something instead of returning it as a string, especially as for libraries.” My thinking was not completely wrong, but the exception I mentioned and which the developer mentions – concerning “manipulation of the output” or “forced output” – turns out to be more common in WordPress than I recognized.

The use has to do with establishing code extensibility. As WordPresser Pippin Williamson put it in a useful post from 2012, making a WordPress plugin extensible means writing it so that “other plugins and themes can manipulate or add onto the behavior of the plugin.” The “WordPress way” to achieve this end is to include “action hooks” and “filters” at critical points. It turns out that for the kind of script in which I am interested, the ob_start() to ob_get_clean() sequence is just what I need.

In my own StackOverflow answer  to my own question, posted today, I wrote the following:

In order to provide a filter – using the common WordPress “apply_filters” function – you will frequently need to be able to capture the entirety of your HTML output at once. When creating a large, complex block with mixed HTML and secondary functions, using an ob_start()/ob_get_[] sequence will be a markedly more efficient way of achieving this end.

So: A plugin on which I’m currently working outputs a table whose elements are put together using a number of secondary functions. Now, I could conceivable do the entire thing adding content to a single variable, but it’s much easier and more economical to initiate output buffering at the beginning, and then write the code without the extra layer of abstraction of $html .= [more and more HTML and PHP] In the end, the code assigns the entire output to a variable:

$html = ob_get_clean();

It then returns the variable with the apply_filters function:

return apply_filters( 'filter-tag' , $html );

Additionally, ob_start() and ob_get_clean() mark points in the code where it makes sense to provide do_action hooks.

In the Link-Posts Aggregator plug-in that I’ve been working on for the last month or two, at line 150 (as of this writing) of the main output function, the code finally turns to the main WordPress query that will produce the actual content of the table. In a sequence that I’m thinking may become a common sight in my plug-ins of this general type, lines 152-6 read as follows:

After 86 lines, including action by 4 html-outputting secondary functions, the query loop has finished, and the total output can now be captured – and hook-and-filtered:

Now I – or any developer – can add functions at the “do_action” points, or can perform more complex manipulation of the “$html” content.

How to use apply_filters is something that has taken me a long time to grasp: I wish I had come across Williamson’s post when first seeing the function in WordPress core code (years ago by now), and having no idea how to exploit it!


WordPresser
Home Page  Public Email  Twitter  Facebook  YouTube  Github   

Writing since ancient times, blogging, e-commercing, and site installing-designing-maintaining since 2001; WordPress theme and plugin configuring and developing since 2004 or so; a lifelong freelancer, not associated nor to be associated with any company, publication, party, university, church, or other institution. 

Posts in this series

Commenter Ignore Button by CK's Plug-Ins

Leave a Reply

Your email address will not be published. Required fields are marked *

*

WordPress Plug-In Notes

  1. Realizing the Commentariat (May 8, 2015)
  2. Child of Mog; Extraordinary Comments (May 25, 2015)
  3. Patronize 'Em: WordPress Draft Post Docket with Subscription and Donation Options (June 9, 2015)
  4. Realizing The Commentariat: Phase 2 (June 22, 2015)
  5. Pseudo-Redacting Spoilerer (July 25, 2015)
  6. Spoiling you some more (August 5, 2015)
  7. Testing Ajaxified Comments - Experiment Halted (August 11, 2015)
  8. New New Since Last Visit Comments Comments (August 16, 2015)
  9. WordPress Comment Nesting Unbound (August 22, 2015)
  10. The Snake Is Implemented (August 25, 2015)
  11. Comments Since Last Visit Reloaded, Reloaded, Testing Post (August 31, 2015)
  12. Comments Since Last Visit, Reloaded, Augmented, Installed, In Two Steps (September 13, 2015)
  13. Coming Soon (I Think!): Author Bios (September 25, 2015)
  14. How to Do Backlinking Footnotes (November 30, 2015)
  15. Who or What Is Using "Commenter Archive" and "commenter-thread"? (February 16, 2016)
  16. Enabling WordPress Press This for HostGator Sites (March 9, 2016)
  17. Linkback Your Xpost: A Simple WordPress Filter Function (March 14, 2016)
  18. Add Amazon Affiliate Tags to WordPress Posts <i>and</i> Comments Automatically (March 19, 2016)
  19. Finding Lost WordPress Widgets after Core Upgrade (March 21, 2016)
  20. Plug-In Away... and the Iron Law of Irony (April 16, 2016)
  21. To o-b or not to o-b (output-buffering in WordPress) - UPDATED (April 24, 2016)
  22. Output-Buffering and Extensible WordPress Plug-Ins (May 21, 2016)
  23. Getting Right with Image Rights: WP Replace Unlicensed and Broken Images Plug-In (June 17, 2016)
  24. Getting Right with Image Rights: Workflow and Major Minor Upgrade (June 27, 2016)
  25. Getting to Better WordPress Twitter oEmbed (June 28, 2016)
  26. An Alliance of Digital Artists (Art and Work in the Age of Instant Reproducibility) (July 8, 2016)
  27. Comparative Page Loads with and without Image Errors (July 14, 2016)
  28. jQuery-Filling an Input Box in WordPress Admin (July 15, 2016)
  29. Drilling a Hole in the Universe with WP_Query in a Shortcode (September 1, 2016)
  30. Troll-Stomping and Other Sensible Things: #WordPress Plug-In Beta Test/Preview (November 12, 2016)
  31. Commenter Ignore Button Preview Video (November 30, 2016)
  32. Is This Solution for Caches vs Cookies Going to Get Me in Trouble? (November 30, 2016)
  33. Commenter Ignore Button 0.99 (December 21, 2016)
  34. Adding wp.media Multiple Image Selection to WordPress Plug-Ins (January 5, 2017)
  35. Working around an Unexplained Failure of WordPress {$taxonomy} Hooks (January 10, 2017)In Progress: Subscribe!
  36. Better Twitter Embeds 2: Stripping the Convo for the Sake of the Convo (February 19, 2017)

Noted & Quoted

(0)

[C]limate scientists have a strange kind of faith: We will find a way to forestall radical warming, they say, because we must.

It is not easy to know how much to be reassured by that bleak certainty, and how much to wonder whether it is another form of delusion; for global warming to work as parable, of course, someone needs to survive to tell the story. The scientists know that to even meet the Paris goals, by 2050, carbon emissions from energy and industry, which are still rising, will have to fall by half each decade; emissions from land use (deforestation, cow farts, etc.) will have to zero out; and we will need to have invented technologies to extract, annually, twice as much carbon from the atmosphere as the entire planet’s plants now do. Nevertheless, by and large, the scientists have an enormous confidence in the ingenuity of humans — a confidence perhaps bolstered by their appreciation for climate change, which is, after all, a human invention, too. They point to the Apollo project, the hole in the ozone we patched in the 1980s, the passing of the fear of mutually assured destruction. Now we’ve found a way to engineer our own doomsday, and surely we will find a way to engineer our way out of it, one way or another. The planet is not used to being provoked like this, and climate systems designed to give feedback over centuries or millennia prevent us — even those who may be watching closely — from fully imagining the damage done already to the planet. But when we do truly see the world we’ve made, they say, we will also find a way to make it livable. For them, the alternative is simply unimaginable.

Comment →
(1)

They were concerned that any pre-election response could provoke an escalation from Putin. Moscow's meddling to that point was seen as deeply concerning but unlikely to materially affect the outcome of the election. Far more worrisome to the Obama team was the prospect of a cyber-assault on voting systems before and on Election Day. They also worried that any action they took would be perceived as political interference in an already volatile campaign. By August, Trump was predicting that the election would be rigged. Obama officials feared providing fuel to such claims, playing into Russia's efforts to discredit the outcome and potentially contaminating the expected Clinton triumph.

This, right here. This is where they choked. The American people had damned close to an absolute right to the information their government already had. The most fundamental act of citizenship is the right to cast an informed vote. The idea that the Obama administration withheld the fact that the Russians were ratfcking the election in order to help elect a vulgar talking yam is a terrible condemnation of the whole No Drama Obama philosophy. Would Donald Trump have raised hell if the White House released what it knew? Of course, he would have. But, as it was, the American people went to vote with only about half of the information they needed to assess his candidacy. This was a terrible decision.

Comment →
(0)

Changing views of U.S. presidents over past decade and a halfAs Pew Research Center’s global surveys from George W. Bush’s presidency illustrated, many of Bush’s key foreign policies were unpopular, and by the time he left office Bush was viewed negatively in most of the countries we polled. His successor, Obama, generally received more positive ratings throughout his White House tenure.Today, in many countries, ratings for President Trump look very similar to those for Bush at the end of his term. This pattern is especially clear in Western Europe. In the UK, France, Germany and Spain, the low levels of confidence in Trump are very similar to the poor ratings for Bush in 2008.

Comment →

State of the Discussion

Wade McKenzie
Comments this threadCommenter Archive
+ …the desperate last-gasp radicalism of American reactionary conservatives before the demographic deluge and the expected relegation of white-European Americans to “minority” status in “their own” [. . .]
Holy American Major League of Nations (Notes on Baseball and the Re-De-Nationalization of Americanism)
Wade McKenzie
Comments this threadCommenter Archive
+ Speaking of George Friedman... The party of Chancellor Angela Merkel no longer uses the word “friend” to describe the United States in its platform. But in [. . .]
German Trust in America – the Trend (#OAG 12b)

just a note on your observation about the whiskey rebellion

https://youtu.be/ASZ7NXD4i1s

Holy American Major League of Nations (Notes on Baseball and the Re-De-Nationalization of Americanism)

Extraordinary Comments

CK's WP Plugins

Categories

Related