Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
content_for and yield in php (specifically wordpress)
* A simple `content_for` and `yield` function to make it easier to run custom JS and CSS
* in the context of templates. Works like the Rails methods of the same name.
* Requires PHP 5.3 or higher (it uses closures, which were added in 5.3)
* Original Source:
* Usage:
* <?php
* // in a template
* content_for('javascript', function() {
* tracking_link_observer();
* });
* ?>
* <?php
* // in your layout
* yield('javascript');
* ?>
$contents = array();
function content_for($name, $method) {
global $contents;
$contents[$name] = $method;
function yield($name) {
global $contents;
if(array_key_exists($name, $contents)) {
return $contents[$name]();
Copy link

polarblau commented Dec 20, 2012

Looking for an implementation of content_for to be used with PHP and Wordpress I came across your Gist and would like to point out that this doesn’t work exactly like Rails’ version. It’s not possible to yield for content before it has been set. (Which is what I’m after :) .)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment