Building and Managing Dynamic Multi-part Pages with WordPress

Twenty Seventeen is the first bundled theme to provide a way to create multi-part pages with WordPress, via a front page sections option that features multiple pages on the front page. This is useful for largely single-page sites, but limits the functionality of a front page as a showcase for and gateway to content throughout larger sites.

For sites with more content, and even multiple post types, there isn’t an established pattern for building pages that feature multiple pieces of content. Core archives exist for single taxonomy terms, authors, and post types, but widgets or custom implementations are needed to tie these pieces together. Twenty Fourteen explored strategies for high-content sites by providing numerous widget areas, specialized widgets, and featured content on the front page. The featured content concept provides two major benefits: visitors are exposed to a diverse array of content that would otherwise be buried deeper in a site, and the featured items are updated automatically as new content is created.

WordPress is especially strong in its use of taxonomies to group content together. Extending this functionality one more level to allow terms and posts to be grouped into navigational indexes provides immense power to build complex pages that can be managed within WordPress rather than being defined in code. Featuring taxonomy terms in addition to single posts makes these multi-part pages dynamic, with featured content updating automatically as new items are published.

It can be difficult to visualize the end goal for these types of pages, so here are a few examples of dynamic multi-part pages that should be possible to build and manage with WordPress:

Suggested Solution: Menus

WordPress menus organize navigation to different elements of a site. This is traditionally handled as vertical or horizontal lists, often with hierarchy. Recently, themes have expanded this concept by presenting additional layouts such as social menus that display icons in place of text labels. Some themes show the menu item’s description (a core feature) for additional context.

From a technical perspective, menus have a dedicated post type with a post for each menu item, and a taxonomy term for each menu to group the items together. I became far too familiar with the benefits and challenges of this approach in the year that I spent bringing menu management into the customizer with live preview. The potential to do more with menus struck me as the biggest opportunity for themes (and plugins) to innovate site management without major core changes.

The basic concept of a menu is a way to organize content on a site. And in core, menus can contain items for posts and terms of any type (that supports it), as well as custom links. What if we took this concept a step further, encouraging themes to pull additional elements such as featured images or even post excerpts or content from the objects associated with menus?

While this may seem like an odd proposal if you think of menus as primarily useful for navigation, setting this up in a dynamic way actually preserves the organizational intent by providing navigation to content within the site. The difference is that more context is available for each item, and some items may be presented largely in their entirety without linking off to a single post view, perhaps enabling the option for more of a single page site feel. Taxonomy terms featured in a menu could display the first few posts within them as well as any taxonomy meta and the term description, opening the doors for a deeper showcase of content with a menu and introducing dynamic hierarchy by showing content within terms.

Perhaps the biggest advantage of this approach is that it can be implemented right now with the support of a robust management interface with live preview in WordPress core. You don’t need to build any backend functionality – core provides it already with the ability to select any content from the site to add to a menu, reordering with drag and drop, and live preview of the end product in the customizer out of the box. Everything is easily portable across themes, with menus needing assignment to the appropriate locations but otherwise persisting across theme switches. There are things that core can do to improve the experience further for developers and users, but it works today. If theme developers begin to experiment with using menus to build and manage multi-part pages, users stand to benefit significantly in their ability to control how they present their content.

I should note that this is not “content blocks.” While that term typically refers to improved management of content within a post object, this proposal is intended to improve the way that different pieces of content can be organized.

Proof of Concept: Dynamic Seventeen Theme

To showcase this concept, in both code and a functional theme, I’ve created the Dynamic Seventeen theme. A child theme of Twenty Seventeen, it replaces the static page-based front page sections with dynamic menus-based content. It also adds a page template that turns any page into a dynamic content page, automatically creating an associated menu location for each page with the template. Page templates are not a fantastic experience currently, but this is a good example of how they can provide useful functionality.

Dynamic Seventeen sticks with the base design of Twenty Seventeen, featuring a list-type layout interspersed with large featured images. It also extends the concept of the two column layout by providing the ability to add subtitles or descriptive text to each section, under the post title. Leveraging the menu item description field for this is an example of how menus can provide additional functionality over other approaches without custom admin UI.

The child theme is currently pending review for the WordPress.org repository, so it is available here for now. The code is not particularly complex, using a custom nav menu walker to retrieve information about objects associated with menu items and display templates matching the rest of the theme. I encourage theme developers to take this first example and adapt it to their themes, adjusting exactly what content is shown, what content types are supported (for example, not showing custom links), and the markup and styling of the results as needed.

Gif demonstration of setting up the Dynamic Seventeen themr in the customizer with menus.
Dynamic Seventeen dynamic content management with menus demonstration.

The Future of Dynamic Multi-part Pages in WordPress

Dynamic, multi-part pages are an important aspect of many larger sites because they offer a gateway to a diverse array of content in the site. But if site owners are unable to manage their content without hiring a developer, WordPress is only realistically useful in the long run for businesses with in-house development teams. Empower users to organize and showcase their own content by creating usable interfaces with live preview, allowing them to trust that their changes work as intended.

While the menus approach works without any core changes, there are several things that would make the user experience better for this and other innovative uses of menus:

  • #38957 – Customize Menus: Menu locations should be able to opt-out of menu item types that can be added to associated menus
  • #38956 – Customize Menus: menus assigned to locations with limited depths should not allow deeper depths
  • #18584 – Nav menus need more hooks for extensibility

There is also a core ticket to expand the functionality of static multi-part pages like Twenty Seventeen’s front page. I remain skeptical of this approach because of the significant technical debt and future maintenance associated with the major additions proposed, and the redundancy with the existing functionality of menus. Let’s improve what we have and build on it rather than turning to new features that duplicate functionality and ultimately further fragment the user experience.

Trust WordPress with Live Preview

When most of us walk into a building, we assume that it’s safe. We trust that it’s built to code and structurally sound. And we trust that the engineers and architects behind the building know what they’re doing.

If a room is too hot or cold, bright or dim, spacious and sprawling or tight and cramped, many people are uncomfortable and may even complain. Human comfort is the most important aspect of the design of physical space, yet it is nearly impossible comprehensively assess the experience of a space before it’s built.

The disconnect between designing a space and experiencing the end product is the biggest challenge in the building design industry. Digital products face similar challenges in bridging the gap between designing something and publishing it, but physical constraints pose fewer challenges here. WordPress has evolved to provide the potential to close this gap all the way to an end user managing content, by providing a framework for live previewing changes to a site before publishing them.

To fully understand the significance of live preview in the WordPress context, it is informative to consider examples of similar challenges and solutions in other industries. We’ll start with a few examples before returning to the topic of live preview and WordPress, and examining the importance of trust.

Previews in Structural Engineering

Most people trust structural engineers to design safe buildings and bridges. And engineers work diligently to consider every possible scenario that each structural element and connection may experience. But at the end of the day, most structural engineering problems are ultimately educated guesses.

In structural engineering, the governing equation is design < capacity. In other words, the load on the structure, from its own weight, the weight of its occupants, and environmental forces such as wind, snow, and earthquakes, must be less than the amount of load a given element can support. But both sides of these equations make numerous assumptions. Vertical loads are typically estimated as distributed area loads based on the design usage, while the capacity of a structural element is based on the expected properties of its material and shape. Demand loads are amplified and capacity reduced by safety factors to account for the potential uncertainties in both estimates; these factors of safety help engineers trust their designs despite these uncertainties.

In addition to making significant assumptions at every step of the design process, structural engineers are limited in their ability to preview the performance of a structure before it’s built. Small scale tests can be performed, and newer digital tools can apply known forces, such as historical earthquake data, to digital building models. But it’s impossible to know exactly what forces a structure may encounter throughout its lifetime, or how exactly the structural members will react. At best, structural engineers can be confident in their designs based on the relative safety factors between the estimated demand and capacity of a structure.

Animated gif showing a building frame bent in different vibration modes
Animated modal analysis demonstrating the potential (exaggerated) vibration modes of a building structure during earthquakes. Created with SAP 2000.

I have personal experience in the challenge of previewing the performance of structural designs via my work with concrete canoes. Last year, our team spent three months researching, developing a new design based on theoretical principles, and conducting tests and small scale experiments, to create a new structural design for our concrete canoe. We even built a full-size practice canoe with the new design and tested it in the water before finalizing the design. But despite hundreds of hours of work, our canoe failed during the race competition. We had not considered the ultimate failure mode in our evaluation of structural theory and small scale tests. And despite full scale testing with the practice canoe, this oversight combined with construction variances between the two canoes to result in the failure. Even building and testing a copy of a full structure does not guarantee that the final product will perform as intended, meaning that true previews of structural designs are not possible to create.

Two concrete canoes with three paddlers racing them in the water
USC’s colorful 2016 concrete canoe, That ’70s Canoe in competition at the American Society of Civil Engineers Pacific Southwest Conference, prior to the canoe’s structural failure.

Previewing Architectural Designs

As I mentioned earlier, architects face immense challenges in previewing the experience of the spaces they design. Working with consultants to design every aspect of a space from the shape, layout and dimensions, to the lighting, climate control, and finishes, architects typically draw two-dimensional representations of their designs so that they can be constructed. Technological advances have enabled three-dimensional modeling, from which two-dimensional construction documents are produced, along with more-fully-rendered images that convey the appearance of the finished product.

While construction drawings and renderings provide a visual preview of the appearance of a design, they do not offer a way to experience the space before it’s built. Full-scale mockups of smaller spaces can be built, but they can’t fully represent the context – views, natural lighting, etc. – of the final product. Walkthrough videos rendered from digital models and virtual reality experiences further the ability to visually preview designs, but lack comprehensive consideration of context and environmental comfort factors.

As building information modeling (BIM) evolves, the building design industry will continue to work toward an ability to preview designs as accurately as possible before they’re built. But the biggest challenge is the effort required to preview changes to a design. Current standard procedures for producing high-quality renderings can take weeks and thousands of dollars to produce updated images to reflect design adjustments. Changes can’t be previewed live, maintaining a disconnect between the design process and the finished product.

Live Previewing Music Compositions

Music composition and the design of aural space present similar challenges to the design of physical space. However, with music, every performance and recording will be different. Each group of musicians will interpret the music in their unique way, and the acoustics of the space they perform in will drastically influence their sound. These differences are actually welcomed by musicians, as every performance of a piece is unique.

Despite these challenges, composers have the closest thing to live preview of the examples I’m presenting here, via music notation software. Modern notation software, which typesets music much like Word does for text documents, typically has the ability to play music back after it’s written. Much of this already happens within a composer’s head, or as a piece is composed at the piano or another instrument; the playback functionality is a way to validate that everything comes together as it’s intended. A composer can change a note and immediately play back any part of the piece as needed to evaluate the impact of the change in context. Here’s an example of how this playback sounds, via a woodwind quintet I wrote last year:

Of course, this nearly-live preview is quite helpful but leaves a lot to be desired. Compare it to the following recording from a reading session. There are of course mistakes as it’s a first reading, not a performance. But the music really comes to life with the complex textures interwoven between the different instruments combined with the interpretations of the musicians:

With no two performances identical, the ability to fully preview a work before it’s first performed is limited. But composers can preview their work with a high degree of accuracy via digital playback, in an experience that’s almost live and ultimately does an excellent job facilitating the creative process. Live preview provides composers with instant validation that their ideas are correctly represented in a written piece, building trust that the work will be performed largely as intended.

Live Previewing Digital Publications

Working our way back to WordPress, let’s look at what’s possible with digital works. Many programs enable content to be created and previewed simultaneously by presenting an interface where content elements are directly editable. PowerPoints, PhotoShop projects, and even (to a high degree) Excel spreadsheets offer a preview of the final product as you build it. Other software for creating digital content has (sometimes necessary) disconnects between making changes and previewing the results – video and audio editing software, or things that can’t be immediately rendered such as sharelatex.com show how disruptive this can be to an end user.

Despite technological challenges, most publications intended to be distributed digitally should be able to be previewed live as they’re created. Considering a diverse array of content types on the web and elsewhere, this can certainly be challenging but is possible. Physical constraints such as the context of a particular building site, musicians’ unique interpretations of a piece, or fundamental uncertainty in the estimation of structural demands and load capacity do not apply to most digital works. In designing digital interfaces, software used to publish and distribute content should prioritize providing users with a live preview of changes as they’re made, at the expense of potential technical complexity, because live preview builds user trust in their work.

History of Live Preview with WordPress

As a platform whose goal is to democratize publishing, live preview is imperative to the usability of WordPress. Back in WordPress 3.4, a first attempt to incorporate this functionality was introduced with the theme customizer, Over time this evolved to support widgets (3.9), strategically expand in scope to become a framework for live-previewing any change to a site (4.0), support menu management (4.3), add selective refresh and device preview (4.5), and continue expanding its capabilities as a framework for live preview in 4.7. User trust is the core goal in providing live previews in WordPress.

The WordPress editor has also evolved to leverage live preview (as long as themes provide editor styles), with inline media/shortcode previews helping users trust that pasting a link on its own line creates an embed, for example. The biggest problem here is that the content is taken out of context, making it difficult to accurately preview the results. Opening a static preview in a separate window is the unfortunate current solution, creating an unnecessary disconnect between the writing and previewing processes. Bringing these together in a unified live preview experience would allow users to trust that their content will display perfectly, helping to stimulate their creative process as they publish content with WordPress.

Themes and plugins can extend the core frameworks for live preview that exist currently in WordPress. Implementing features like selective refresh in the customizer is critical for ensuring that the preview is as fast and preserves as much context as possible. Themes and plugins can also leverage live preview for managing dynamic portions of complex sites, extending menus or widgets to control the content featured on a page, for example. These implementations could eventually lead to improved core functionality for site management or even more direct site building with live preview.

Future Potential

As live preview becomes more integrated into the everyday workflow of publishing content with WordPress, users will become ever more confident in the publishing process. Trusting that the end product will match what you’re creating as you make it offers a faster workflow for everyone and improves the quality of content published with WordPress.

There are many ways to expand the scope of live preview in core, plugins, and themes. I see the most substantial potential in content editing – integrating it with the functionality currently in the “customizer” to offer a unified interface for live-preivewing most aspects of a site as users build content. This will surely take substantial effort from core contributors but if more volunteers continue stepping forward to contribute, we could conceivably see content editing with live preview in core within the next year.

Themes and plugins should also continue expanding their use of live preview as a mechanism for managing their functionality. Custom sites with complex frontends are great places to implement live preview – give your users confidence to manage their own content by letting them do so with the context of live preview.

In closing, I want to highlight that the customizer is WordPress’ framework for live-previewing any change to a site. With over four years of development to date, the customize API is already the easiest and most powerful way for developers to extend WordPress, and it’s getting even better with every release. And it supports live preview for any option. Let’s build on that framework, rethinking elements (such as the interface) that should be improved, to make WordPress better for everyone that uses it. With live preview, users can truly trust WordPress.

A Strategy for Custom Colors in the Customizer

The customizer is a framework for live-previewing any change to a WordPress site, and it is particularly useful for previewing visual changes. It has always shipped with a color control and the ability to preview custom colors with little effort, but the previewing experience has often been a bit slow. This post outlines a strategy for custom color options that leverages instant JS-based previewing in conjunction with selective refresh.

Animated gif of the linework theme with its colors changing via the customizer
Demo of instant custom color previews in the customizer with the Linework theme.

Example Plugin: Custom Highlight Color

I’ll leverage the custom highlight color plugin as an example of this approach. I recommend downloading it from WordPress.org to follow along with, and I’ll provide a detailed walkthrough of the code with excerpts here.

This plugin only has one option – the highlight color. However, this approach can easily scale to additional options. As I’ll show later, it’s best to minimize your options and instead rely on code logic to generate or select variations as needed so that users can achieve custom results with minimal effort and decision-making. Finding the right balance of color options is an important step in the product design process, and one where even the past couple of default WordPress themes leaned a bit too far in the direction of options, in my opinion.

Adding Customizer Objects

The first step is to register your color options in the customizer via the PHP API. We can use the colors section provided by core, leaving the setting and control to be registered in your theme or plugin. The transport will be postMessage, indicating that we’ll preview the setting with JavaScript:

function custom_highlight_color_customize( $wp_customize ) {
	$wp_customize->add_setting( 'custom_highlight_color', array(
		'type' => 'option', // Change to theme_mod when using in a theme.
		'default' => '#ff0',
		'sanitize_callback' => 'sanitize_hex_color',
		'transport' => 'postMessage',
	) );

	$wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'custom_highlight_color', array(
		'section' => 'colors',
		'label' => __( 'Highlight Color', 'custom-highlight-color' ),
	) ) );
}
add_action( 'customize_register', 'custom_highlight_color_customize' );

The setting will use sanitize_hex_color, ensuring that a single secure hex color code is saved in the database for each option. For themes, you should set the type to theme_mod instead of option, and it’ll be stored with the rest of the theme-specific options automatically.

Color Patterns and Calculations

Next, we need to define the CSS that will display the custom color options. By putting this into a distinct function, the code can be leveraged in multiple preview and output contexts. When there’s a lot of CSS, I prefer to break this into a separate file to make it easier to maintain. You can even split distinct parts of the color CSS into different functions. For a simple example, here’s what Custom Highlight Color does:

function custom_highlight_color_css() {
	require_once( 'color-calculations.php' ); // Load the color calculations library.
	$background = get_option( 'custom_highlight_color', '#ff0' ); // The second argument is the default color when the theme mod is undefined.
	// Set the text color to black or white, whichever provides higher contrast with the highlight color.
	if ( custom_highlight_color_contrast_ratio( $background, '#000' ) > custom_highlight_color_contrast_ratio( $background, '#fff' ) ) {
		$color = '#000';
	} else {
		$color = '#fff';
	}

	$css = '
		::-moz-selection {
			background: ' . $background . ';
			color: ' . $color . ';
		}
		::selection {
			background: ' . $background . ';
			color: ' . $color . ';
		}';
	return $css;
}

You’ll notice that there are some color contrast checks here, which automatically set the text color to ensure that it contrasts with the highlight color. In this case it looks for the higher contrast between two colors, but typically you’ll want to ensure that the contrast is at least 4.5 between background and text colors. These checks leverage the color-calculations.php functions that I originally developed for the Fourteen Colors plugin. Feel free to take this file from the custom highlight color plugin and ship it with your project (make sure you update the function prefixes to match your plugin or theme).

In addition to the contrast check (which is done per the WCAG guidelines), the color calculations library has a handy function to “adjust” a color. You can use this to brighten or darken a color by a numeric amount, generating color variations automatically. The Fourteen Colors plugin uses this technique extensively.

Color Output

Now that our color patterns are defined, it’s easy to display the color CSS within style tags in wp_head. However, in the customizer preview, we also need an easy way to get the current colors in JavaScript. To do that, we’ll conditionally add the colors as data- attributes when is_customize_preview():

add_action( 'wp_head', 'custom_highlight_color' );
function custom_highlight_color() {
	if ( is_customize_preview() ) { 
		$data = 'data-color="' . get_option( 'custom_highlight_color', '#ff0' ) . '"'; 
	} else {
		$data = '';
	}
?>
	<style type="text/css" id="custom-highlight-color" <?php echo $data; ?>>
		<?php echo custom_highlight_color_css(); ?>
	</style>
<?php }

The colors should now display on the front end, but they won’t preview in the customizer just yet.

Instant Custoizer Previews with JavaScript

To preview the color changes instantly in the customizer, we first need to enqueue a JS file to manage color previews (if your theme already loads a customizer JS file, you can add to that in lieu of introducing another one):

function custom_highlight_color_customize_preview_js() {
	wp_enqueue_script( 'custom_highlight_color_customizer', plugins_url( '/customizer.js', __FILE__ ), array( 'customize-preview' ), '20160830', true );
}
add_action( 'customize_preview_init', 'custom_highlight_color_customize_preview_js' );

In that file, we’ll follow the standard customizer preview conventions and bind to changes on our settings. For each of the colors, we’ll search for instances of the original color in the CSS, and replace them with the new color:

( function( $ ) {
	wp.customize( 'custom_highlight_color', function( value ) {
		value.bind( function( to ) {
			// Update custom color CSS
			var style = $( '#custom-highlight-color' ),
			    color = style.data( 'color' ),
			    css = style.html();
			//css = css.replace( color, to );
			css = css.split( color ).join( to ); // equivalent to css.replaceAll.
			style.html( css )
			     .data( 'color', to );
		} );
	} );
} )( jQuery );

You’ll need to bind changes to each of your color settings if you have multiple color options. Now, you’ll be able to preview color changes instantly in the customizer. But what about the colors generated using color calculations in PHP?

Adding Selective Refresh for Secondary Colors

To supplement the instant JS previewing that updates the CSS with a search-and-replace of the color value, we need to add selective refresh support so that the CSS is re-rendered from PHP with our color calculations applied. The color patterns and calculations could be duplicated in JS, but that would become quite difficult to maintain and offers only a slight usability benefit. With selective refresh, we can leverage the existing function in PHP; it’s only a matter of adding a customizer partial that will be refreshed when one of the associated colors changes:

$wp_customize->selective_refresh->add_partial( 'custom_highlight_color', array(
	'selector'        => '#custom-highlight-color',
	'settings'        => array( 'custom_highlight_color' ),
	'render_callback' => 'custom_highlight_color_css',
) );

This code should be added within the same callback to the customize_register action that we added earlier. Multiple settings can be associated with a single partial; add the other setting ids to the array of settings.

Once that’s complete, you should be able to preview all of your custom colors in the customizer, with instant updates to base colors and updates to generated colors happening on a slight delay. Colors are safely stored in the database without the security issues of saving CSS there, and styles are applied on the front end as expected. I’m now leveraging this approach in all of my themes and plugins as I find it to provide a nice balance between user experience and code simplicity.

The custom highlight color plugin is a simple example, built specifically to be an example, but this approach easily scales to more colors as needed. For a more complex example, check out the code for the Fourteen Colors Plugin or the Figure/Ground theme (which runs this site and lets users customize every color).

An Update for Figure/Ground

I’ve updated my Figure/Ground theme on WordPress.org (which also powers this blog) with a few nice enhancements:

  • All options in the customizer are now instantly live-previewed with postMessage.
  • Add support for selective refresh in the customizer for widgets, and generated colors.
  • There is now a social icon menu.
  • Redraw the background canvas when the page is resized to avoid pixelization.
  • Improve keyboard navigation (although this still needs additional work).
  • Update Genericons to version 3.4.1.

The new customization experience is the most notable enhancement. See every color change instantly as you play with it in the color picker, without any delay. Enjoy!

Interactive Geometry Apps

Three years ago, I created several interactive geometry apps while working for Saltire Software. As part of the process, I built the collections functionality for Euclid’s Muse (which I had created the previous year at Saltire), which includes the ability to download a collection of web-based applets as a standalone mobile app that can be processed through PhoneGap and published on app stores. The original intent was to publish a few of these apps on the app store and Google play myself, but I never got around to it. So, I decided to publish them as another site on celloexpressions.com. The five apps are:

I also created an index page based on the pseudo-random experiments page. I’m thinking about turning it into a simple WordPress theme with a fun background (animation off by default), anyone interested?

Featured Audio in WordPress

Featured images are native to WordPress core, allowing themes to represent posts and pages with images. But for many users, there are more important content formats than visuals. As a musician, I’ve explored different approaches to integrating WordPress’ audio functionality with post objects, most recently with the Sheet Music Library plugin.

I recently began exploring a new idea — a premium WordPress theme built specifically for musicians and musical groups — and I realized that WordPress needs a generic solution for the broad concept of associating audio files with posts. Post meta associated with specific custom post types or embedding audio directly in posts limits the opportunities for themes to display audio in unique ways and for plugins to create aggregated presentations of audio associated with different posts.

The Plugin

Screenshot of the featured audio option
Featured Audio metabox in the editor.

Seeking to introduce a broad solution to the challenges of deeply integrating audio with core WordPress functionality, I’m introducing the Featured Audio plugin. Featured audio is perfect for musicians, podcasters, and anyone who publishes audio content on their site frequently. It works with every theme out of the box by displaying WordPress’ native (mediaelement.js) audio player at the top of the_content. Themes that style the audio player already will offer a customized experience for site visitors using featured audio.

Screenshot of featured audio for the twent fifteen theme
Default featured audio display with the Twenty Fifteen theme.

I’d love to see more themes designed specifically to make audio a central component of sites’ content. If they all leverage this standardized featured audio plugin, users publishing audio content can get a wide variety of options for displaying their content and the content adapts seamlessly from theme to theme, just like publishers of visual content get with featured images.

The Importance of an API

To make featured audio as broadly extensible as possible, I spent a significant amount of time building public API functions into the plugin that facilitate custom implementations and integrations. Where it makes sense, these functions parallel the post_thumbnail/featured images API in WordPress core. However, the most notable difference is that theme support isn’t required. Taking a similar approach to the Featured Image in Content plugin (but also always showing the admin UI), the content is available regardless of theme support to allow a broader array of themes to be used. Theme support is used to indicate custom implementations, and turns off automatic front-end display of featured audio on a technical level.

A majority of sites probably don’t use audio at all, making the idea of featured audio probably inappropriate for WordPress core. But by building a core-like solution that themes and other plugins can extend, we can provide audio publishers with similar opportunities to publish freely with WordPress. And the development of themes and plugins that extend and customize the experience will further promote publishing audio with WordPress.

Infinite Possibilities

Once the base API is in place via the Featured Audio plugin, there are endless possibilities for themes and plugins to expand the potential of featured audio to offer tools for publishers. Plugins can expand the API to offer additional functions for custom theme display, or other tools such as widgets or shortcodes to aggregate featured audio across posts. The core playlist functionality is especially promising here.

Themes can do anything from moving where featured audio is displayed or adding it to archive views that don’t display the content to showcasing audio in unique and unexpected ways in the front-end UI. We’ve seen featured image headers, so why not featured audio headers, with the ability to set up a default audio file in the customizer. I’m excited to see what theme designers can come up with.

Screenshot of a featured audio playlist entitled "featured on this page"
Feadured Audio Playlist widget in the Twenty Fifteen theme.

To offer a glimpse of the possibilities, I’ve built a few advanced features into the plugin. The API includes arguments for the main the_featured_audio() function to display the title and/or album art (which WordPress automatically pulls from MP3 files that have it) alongside the audio player for easy display of additional information in themes. The plugin also adds a Featured Audio Playlist widget, which displays a playlist with all of the featured audio associated with posts on the current view, such as a blog index, archive, or taxonomy page. The playlist output is also available directly via an API function for custom display in themes outside of the widget context. For example, a playlist could be displayed alongside a taxonomy title and description at the top of a taxonomy archive. Playlists are great because they allow visitors to listen to more of your content without repeated manual interactions, and in this scenario they’re automatically created and organized on-the-fly based on the existing organizational structure of a WordPress site.

Content Ownership and Hosting

One of my personal goals with featured audio is to encourage publishers to host their own audio content directly in their WordPress site. Third-party services such as Soundcloud offer advantages in distribution but when it comes to displaying content on sites, I frequently get the impression that users don’t realize that they can host and publish their audio content directly. WordPress is about democratizing publishing, and part of that mission is to give users complete control over their content. With better resources for publishing audio directly in WordPress, fewer users will feel a need to turn to third-party services. Long term, it would be awesome to see third party social and aggregation sources for audio content pulling data out of WordPress sites rather than the other way around, as it is currently.

Next Steps

Now that the plugin is live on the repository, publishers can start using featured audio with the basic experience on any theme out of the box. But the really exciting opportunities come with plugins and themes that extend the basic experience, and it’s up to you to start designing and building those projects. I’m hoping to build a commercial musician-oriented theme that integrates with featured audio eventually, but the beauty of open source software is that anyone can create free or commercial products that build on this functionality. I’m excited to see what the community can do together to improve the experience of publishing audio content with WordPress.

The Customizer is the Future for Themes and Theme Options

There has been a lot of backlash from the WordPress community recently over the theme review team’s decision to require theme options to be implemented in the Customizer. But this decision really is in everyone’s best interest.

WordPress 4.2 shipped with the ability to switch themes in the Customizer. When theme-installation is incorporated in a future release, the entire theme selection and customization process will be streamlined to a seamless workflow in which the user never enters the WordPress admin. This functionality is specifically targeted to users that leverage free WordPress.org themes, so it just makes sense for all themes hosted there to be Customizer-optimized. But the real win is the ability to live-preview changes before publishing them. With the Customizer, users know exactly what their site will look like when they publish their changes, a critical feature for anyone who cares what their site looks like when it’s publicly available.

Many people have been critical of the user-oriented nature of the Customizer. But its power is much stronger than most realize; one of my favorite use-cases for the customizer is custom CSS. This is the easiest way for users who want to go further to get into coding and offers a seamless experience that is infinitely better than the easy-to-kill-your-site-or-lose-your-changes-with code editor in the admin. In fact, I’d love to see a customizer-based custom CSS functionality in core as a replacement for the code editor, although I have a feeling that proposal may be too political to advance to an implementation. Bottom line, the customizer lowers the barrier to entry into WordPress development, contrary to many people’s thinking.

Yes, free themes requiring use of the Customizer will lead to a similar movement for client themes and premium themes. And that’s okay. In fact, by having everyone using the same underlying framework, users know where to look for options and have the confidence that live previewing provides. And WordPress will provide a more consistent visual experience for users as well.

You can really build any functionality into the Customizer. Theme-switching, widgets, and menus were all built as plugins first and continue to use the publicly available customizer API to run. So if you must, you can still create ridiculously complicated UI elements that no one will be able to figure out how to use, but you really don’t need to.

And complaints about the amount of screen real estate available and the 300px default width show a lack of creativity and resistance for the sake of resistance to change. Start by removing all of the ads, external links, unnecessary branding, unnecessary options, and general clutter. Make your options self-explanatory – if you need a paragraph to describe what it does, it probably shouldn’t be a user-facing option. Do you still have so much UI that the experience is completely unusable? Try an outside-the-box solution, like utilizing the core media modal (header images and core media controls use it), a custom modal (theme details modal in core), or a slide-out panel (widgets in core and eventually menus in core as well).

No, the customizer isn’t perfect. But it’s time to give it the respect it deserves as a significant part of WordPress. After three years of slow adoption, the theme review team’s decision to enforce its use is a welcome sign for users and a positive decision for the WordPress community as a whole. I’m excited to see what developers do with the Customizer’s amazingly powerful API and what core contributors come up with to improve its design and usability.

Twenty Fifteen, no sidebar

Twenty Fifteen is another great default theme that can be easily customized. I recently had to put up a quick site for my new themes site on halsey.co. I only wanted one or two pages, with a super simple layout.

I decided to just remove the sidebar (remove the widgets first) and center the content area. On mobile, all we need to do is remove the header. This also removes the “proudly powered by WordPress” footer, as there’re better ways to display that in this context if you want it. Here’s the CSS:

body:before,
#sidebar,
#colophon,
.entry-footer {
	display:none;
}

.site-content {
	margin: 0 auto;
	float: none;
	width: 100%;
	max-width: 1200px;
}

If you’re not familiar with CSS, the easiest way to implement this is to install & activate the Modular Custom CSS plugin, then go to the Customizer and add the above CSS to the “Custom Theme CSS” field.

New Sheet Music Library: The Story

After nearly two years of planning, false starts, and development, I finally launched a new sheet music library. In this post, I’ll discuss the development and implementation process, design decisions, and how I created this project in a way that the source code will be available for anyone to use for free.

History

I started posting my cello ensemble compositions and arrangements online in early 2012, when I first set up celloexpressions.com as the website for my high school cello quartet, Cello Expressions. When I transitioned the site to be the home for my projects in August of that year, I created a series of separate WordPress installs for my different sites, moving the original site to the music subdirectory and building a new system to display sheet music in a more structured way. Because I had spent the summer developing Euclid’s Muse, basing the code off of a horribly-written BuddyPress plugin, I thought that the best approach would be to create a custom database table, querying it directly. I didn’t have the time to build a posting or editing UI, so I decided I would just make edits directly in the database with PHPMyAdmin. That worked for a few months, and in November 2012, I redesigned the site’s theme (poorly). But I would last post a new piece in January 2013. It was clear that I needed an entirely different system, and that I would probably need to migrate all of my existing content (now 60 pieces) manually.

Cello Expressions Sheet Music Library, from January 2013 to December 2014.
Cello Expressions Sheet Music Library, from January 2013 to December 2014.

Goals

My primary goal for the sheet music library is to make free music, primarily for cello-oriented ensembles, widely available and accessible. I also want to get my works out there for people to play.

But my goals for making the sheet music library easy to use were much harder to accomplish with the old system. All pieces needed to have PDF downloads, preferably with the ability to have separate score and parts PDFs. I needed to display previews of the PDFs in a browser-agnostic way, rather than hoping that it would work to put a PDF in an iframe. Pieces needed to have a way to upload and display recordings, both via MP3s and via YouTube videos. Pieces needed to have fields for composers, difficulties, genres, and instrumentations, and values should cross-link between different pieces. And most importantly, I needed everything to be searchable, both internally and via search engines.

A Plugin

One of my first decisions was to build the sheet music library functionality in a plugin. That way I could use an existing WordPress theme and redesign much more easily. Over time, additional benefits became clear – others could use this plugin as well. The Boulder Cello Project will be using it, plus an add-on plugin, to power their internal members site, where they post sheet music for their meetups for members to practice in advance. The plugin will be released on WordPress.org once the initial implementation for the Cello Expressions Sheet Music Library is complete.

Custom Post Type & Taxonomies

It also became clear that I should create a sheet music custom post type, with custom taxonomies providing relationships between pieces. Composers, instrumentations, difficulties, and genres are each custom taxonomies for the sheet_music post type. PDFs for the score and parts and audio file uploads would be stored as attachments, with the attachment post ids stored as post meta in sheet_music posts. YouTube videos are stored by their URLs as post meta as well.

PDFs to Images

The solution to displaying PDF previews in a reusable way ended up being surprisingly simple. By converting the first page of the score PDF to an image, the front-end and admin can display an image preview of the PDF pretty easily. Converting PDFs to images is actually pretty simple in most modern server environments with WordPress’ image editor.

Diving briefly into code, WP_Image_Editor’s ImageMagick implementation makes it incredibly easy to convert PDFs to Images:

/**
 * When a PDF is uploaded, generate a thumbnail image and save it in the attachment meta.
 */
add_filter( 'wp_generate_attachment_metadata', 'prefix_generate_pdf_thumbnail_metadata', 10, 2 );
function prefix_generate_pdf_thumbnail_metadata( $metadata, $attachment_id ) {
	$attachment = get_post( $attachment_id );
	if ( 'application/pdf' === get_post_mime_type( $attachment ) ) {
		// Create a png from the pdf.
		$file = get_attached_file( $attachment_id );
		$pdf = wp_get_image_editor( $file );
		if ( ! is_wp_error( $pdf ) ) { // Most likely cause for error is that ImageMagick is not available.
			$filename = $pdf->generate_filename( 'image', null, 'png' );
			$uploaded = $pdf->save( $filename, 'image/png' );
			if ( ! is_wp_error( $uploaded ) ) {
				$upload_dir = wp_upload_dir();
				update_post_meta( $attachment_id, 'pdf_thumbnail_url', $upload_dir['url'] . '/' . $uploaded['file'] );
			}
		}
	}
	return $metadata;
}

Unfortunately, not all servers have ImageMagick installed. I don’t have it installed locally, and when I went to test on the celloexpressions.com server (hosted by GoDaddy for historical reasons), it wasn’t there. I contacted support and they said I had to upgrade to a newer account, which would involve manually migrating everything (or they could do it for a fee). I’d been wanting to get off of that server for a while anyway, so I took to opportunity to move everything onto one of my existing Bluehost accounts, cleaning up some old stuff that was living on celloexpressions.com in the process. Once I switched the domain over to the new server, everything worked exactly how I had wanted.

Realizing how straightforward it is to create images from PDFs in PHP, and how much room for improvement WordPress has with regards to PDF uploads (both in terms of administration and presentation), I’m going to propose some improvements there for core once I finish this project.

Media & Embeds

In addition to digging into the intricacies of WordPress’ handling of PDFs, I spent some time working on my JavaScript skills to implement previews of uploaded audio and linked videos in the admin. Since I knew I’d be using the plugin at large scale, it was important that the admin UI was as functional and efficient as possible. Audio and video previewing was implemented based on the media wpviews in the main editor. While the result is somewhat hacky and buggy, most of the integration relies on core functions rather than extensive custom logic, and I rarely encountered the bugs in my workflows.

On the front-end, wp_audio|video_shortcode( array( ‘src’ => $url ) ); gives browser-compatible HTML5 audio and video via MediaElement.js. That also gives us a skinned player for YouTube videos that matches the audio player, can be customized with CSS, and seems to reduce the volume of ads. WordPress 4.2 will also add support for skinned Vimeo embeds, and the sheet music library plugin won’t require any changes to support Vimeo and YouTube equally.

In a future update, I plan to explore the possibilities with creating a “collection” of PDFs with the media library, similarly to galleries, audio playlists, and video playlists. If I’m successful with that, it could be used to offer separate files for each part of a piece, instead of requiring all of the parts to be in one PDF (which I manually merge the separate parts into before upload). That could also concievably provide an automated merged PDF file that’s created in PHP, if ImageMagick supports something like that.

Templates

While a custom post type with several custom fields and taxonomies would normally work best with custom theme templates, I wanted the sheet music library to be as theme-compatible as possible. So I implemented default templates for single and archive views by filtering the_content. It works pretty well on a lot of themes, and could look just fine on pretty much any theme with a little custom CSS. For more advanced implementations, custom templates and adding theme support for ‘sheet_music_library’ will do the trick. I also created a shortcode that outputs the table view that I use on the homepage.

Search, taxonomies, archives, etc. all work well with the content filtering. The sheet music post type also supports featured images, so using the theme’s templates ensures that images are still used as intended. In my case, I only use images on a few pieces, and they really stand out in search, taxonomies, and post navigation.

Themes & Design

The plan all along was to go with a WordPress.org theme for the initial roll-out, then come back and do a custom theme specifically for use with the sheet music library plugin. But after exploring tons of potential theme options (while testing the theme compatibility of the plugin), I ended up going with Twenty Fifteen. And I’m liking it so much that I may not even do a child theme (I currently have some custom CSS, but that’s it). While I’m not happy with every component of the theme, the biggest things that made it my choice are its strong, scalable typography and its sticky sidebar functionality. CelloExpressions.com has a global header that’s displayed on all sites in the network, and by having no header and a minimal sidebar for the theme, I was able to keep things simple while still providing means for navigating throughout the site. In fact, I ended up with no menu for the music library, leaving navigation and discovery to search and a widget for each custom taxonomy.

My biggest problems with Twenty Fifteen were lack of color contrast, and excessive whitespace/inefficient use of space in places. For a while I had planned to use Twenty Fourteen, since it provides so much space for navigation and is very space-efficient. But upon further investigation, the only part of the sheet music library requiring more horizontal space is the table view on the homepage, so I just dropped some margins there. The contrast issues were a quick fix with Twenty Fifteen’s custom color options, combined with the dark “global” Cello Expressions header.

I also designed a new logo for myself and Cello Expressions as part of this process. I started out on paper, from doodles that had been done while trying to stay awake during class. As I learn more about graphic design, I’m pleased with my final result, and it works great in vector format. Currently, I’m using it in the header and as the site icon. I’ll use it elsewhere as opportunities arise.

Cello Expressions Logo

Migration & New Content

Once the new plugin was finally complete and I’d settled on using Twenty Fifteen at least initially, I was ready to migrate the 60+ pieces from the old site to the new site and add all of the music from the past two years that never made it into the old system.

Because the old implementation was so bad, and most of the old fields wouldn’t translate cleanly to the new taxonomies for composers, instruments, difficulties, and genres, I had to manually migrate all of the content. This also gave me the opportunity to remove some pieces that weren’t up to my current standards.

I started by moving the entire contents of my old server to the new Bluehost server, renaming the /music/ directory to /music-archive/. Then, once I moved the nameservers, I created a new site in the celloexpressions.com multisite network, at /music/. After putting some text in the homepage and setting up my plugins, I started migrating content.

In the end it took nearly two weeks and countless hours, but I now have 104 pieces in my new sheet music library. About half were migrated from the old library, and the other half are newly-published. At a rough estimate, two-thirds have an audio or video recording, or both. They all have scores, terms in four taxonomies, and publication dates back-dated to when they were created. While it required a colossal effort that’s still not quite complete, this project was very much worth it. And the best part is that all of the work, from the software powering it to the music it contains, is free for anyone to use, in the spirit of open source.