Make WordPress Core

Tagged: dev-notes Toggle Comment Threads | Keyboard Shortcuts

  • Aaron Jorbin 9:05 pm on December 5, 2016 Permalink |
    Tags: , dev-notes,   

    WordPress 4.7 Field Guide 

    WordPress 4.7 is shaping up to be the best WordPress yet!  Users will receive new and refined features that make it easier to “Make your site, YOUR site”, and developers will be able to take advantage of 173 enhancements and feature requests added.  Let’s look at the many improvements coming in 4.7…

    RESTing, RESTing: 1, 2, 3

    The foundation for RESTful APIs has been in core since 4.4, and 4.7 sees the addition of Content Endpoints after a healthy discussion. We’ve defined four success metrics as part of the merge discussion and you can help by building themes and plugins on top of the API, using the API in custom development projects, and utilizing the API for a feature project, core features, or patches. So, dive in, start playing around, and let us know what you build!

    REST API Merge Proposal, Part 2: Content API


    It don’t mean a thing, if you ain’t got a theme

    No matter if you are building themes for public consumption, as a bespoke project for a major public company, or anything in between WordPress 4.7 has something to help you.

    Theming with Twenty Seventeen

    Video Headers in 4.7

    Starter content for themes in 4.7

    Visible Edit Shortcuts in the Customizer Preview

    Whitespace changes in navigation for 4.7

    Post Type Templates in 4.7

    New Post Type Labels in 4.7

    New Functions, Hooks, and Behaviour for Theme Developers in WordPress 4.7

    The Voyages of USS Media

    Two notable changes, enhanced PDF support in the media library and changes to the default fallbacks for image alt attributes, are explained in separate posts.

    Enhanced PDF Support in WordPress 4.7

    Improving accessibility of image alternative text in 4.7

    Media also received other exciting enhancements and bug fixes you should check out.

    Around the World

    The way users understand the words on WordPress are important and now users will be able to select their personal preferred language.

    User Admin Languages and Locale Switching in 4.7


    For Whom Customization Tolls

    The customize component will now support the ability to create pages within live preview during site setup; will have a faster, smoother, and more accessible navigation; will automatically persist your changes in the background while you browse your site and switch themes; and will let you fine-tune your site with custom CSS.

    Customizer Improvements in 4.7

    Customize Changesets Technical Design Decisions

    Changes to Customizer Sliding Panels/Sections in WordPress 4.7

    Extending the Custom CSS editor


    Reading, Writing and Teriffic

    Whether you’re creating content in the WordPress Admin or concerned about comment moderation, we’ve got updates that will be sure to please you.

    Editor changes in 4.7

    Comment “allowed” checks in WordPress 4.7


    The Foundation of WordPress

    For those who like to get “under the hood” of WordPress, we’ve got some improvements that will hopefully make your life easier.

    Changed loading order for current user in 4.7

    Multisite Focused Changes in 4.7

    Attributes for Resource Hints in 4.7

    wp_list_sort() and WP_List_Util in 4.7

    WP_Taxonomy in 4.7

    Fine grained capabilities for taxonomy terms in 4.7

    WP_Hook: Next Generation Actions and Filters

    Registering your settings in WordPress 4.7


    But Wait, There is More!

    Over 447 bugs, 165 enhancements, 8 feature requests, and 15 blessed tasks have been marked as fixed in WordPress 4.7. Some additional ones to highlight include:

    • Make media library searchable by file name (#22744)
    • Improved Custom Background Properties UI (#22058)
    • Hue-only Color Picker (#38263)
    • Fix Sections that .cannot-expand (#37980)
    • Allow Plugins to do Comprehensive Late Validation of Settings (#37638)

    Please, test your code. Fixing issues now, before 4.7 is released, helps you and helps millions of WordPress sites.

  • Nick Halsey 10:14 pm on November 30, 2016 Permalink |
    Tags: , , dev-notes   

    Customizer Improvements in 4.7 

    WordPress 4.7 has been the most active release on record for the customize component, with four major feature projects merging and shipping with 4.7 and over 90 tickets closed as fixed. This post summarizes the highlights of the user and developer-facing changes.

    4.7 Customizer Feature Projects

    Create pages within live preview during site setup

    Add new pages while building menus and setting a static front page; outline your site directly in the customizer.

    This project began with the ability to create posts and pages direction from the available menu items panel in the customizer, as originally proposed near the end of the 4.6 cycle:

    Feature Proposal: Content Authorship in Menus, with Live Preview

    Subsequent changes also added the ability to create new pages when assigning the front page and posts page in the Static Front Page section. Because this is now built into the core dropdown-pages customizer control, themes and plugins can also allow users to create new pages for their options instead of relying on existing content. The homepage sections in Twenty Seventeen include this new allow_addition parameter. Here’s how to register a dropdown-pages control supporting new pages:

    $wp_customize->add_control( 'featured_page', array(
    	'label'          => __( 'Featured Page', 'mytextdomain' ),
    	'section'        => 'theme_options',
    	'type'           => 'dropdown-pages',
    	'allow_addition' => true, // This allows users to add new pages from this dropdown-pages control.
    ) );

    Additionally, a proposal for term statuses was developed as a first step toward expanding the menus functionality to work for creating and previewing taxonomy terms in a future release (see #37915).

    Improvements to the Sliding Panels UI

    Customizer navigation is now faster, smoother, and more accessible.

    This project tackled a series of tickets focused on improving the usability of the “sliding panels” UI in the customizer controls pane. The first step was to refactor the section and panel markup so that sections and panels are not logically nested. This is the biggest internal change to the UI and has a dedicated post going into the details:

    Changes to Customizer Sliding Panels/Sections in WordPress 4.7

    This primary change resolved numerous problems with sections and panels not opening and closing properly, and eliminated situations where navigation to leave a section could become hidden. The next step was making section and panel headers “sticky” so that navigation is easier to access within long sections (such as for a menu); see #34343.

    Finally, hover and focus styling for navigation in the customizer has been updated to use the blue-border approach found elsewhere in core, including for the device-preview buttons in the customizer, in #29158. This completes a refresh of the customizer controls pane’s UI design that began in WordPress 4.3 with #31336. The core UI now uses the following consistent UI patterns in the customizer:

    • White background colors are used only to indicate navigation and actionable items (such as inputs)
    • The general #eee background color provides visual contrast against the white elements
    • 1px #ddd borders separate navigational elements from background margins and from each other
    • 15px of spacing is provided between elements where visual separation is desired
    • 4px borders are used on one side of a navigation element to show hover or focus, with a color of #0073aa
    • Customizer text uses color: #555d66, with #0073aa for hover and focus states on navigation elements

    Plugins and themes should follow these conventions in any custom customizer UI that they introduce, and inherit core styles wherever possible.

    Any custom sections and panels, as well as customizations to the core objects in plugins and themes, should be tested extensively to ensure that they continue functioning as intended with all of these changes in 4.7. It’s particularly important to ensure that things like the use of color match the core conventions so that the user experience is seamless between functionality added by plugins and core.

    Customize Changesets (formerly Transactions)

    Browse your site and switch themes more seamlessly within the customizer, as your changes automatically persist in the background.

    This project rewrote the internals of the customizer preview mechanism to make changes persistent. Each change made to a setting in the customizer is saved to a changeset (a new customize_changeset post type), facilitating future features such as scheduled changes, revisions, or saving and sharing drafted changes. Changesets also open the door to using the customizer to preview Ajax requests, headless sites, and REST API calls for mobile apps. In 4.7, changesets enable switching themes in the customizer without needing to decide between publishing or losing your customizations, as they’re automatically persisted in the background.

    For more details on changesets, check out the two dedicated posts:

    Customize Changesets (formerly Transactions) Merge Proposal

    Customize Changesets Technical Design Decisions

    Custom CSS

    Fine-tune your site and take your theme customizations to the next level with custom css in the customizer.

    #35395 introduced a user-oriented custom CSS option in the customizer. Now that the base functionality is in place, it will be further enhanced in #38707 in future releases. Read the feature proposal for details on the implementation and why it’s important for core:

    Feature Proposal: Better theme customizations via custom CSS with live previews

    There’s also a dedicated post that walks through the process of migrating existing custom CSS options in themes and plugins to the core functionality – be sure to follow those steps if your plugin or theme does custom CSS:

    Extending the Custom CSS editor

    Other Changes with Dedicated Posts

    4.7 features several other features deserving special attention. Read the posts for visible edit shortcuts (which expand the functionality of customizer partials), video headers (which extend the custom header feature), and starter content for more information:

    Visible Edit Shortcuts in the Customizer Preview

    Video Headers in 4.7

    Starter content for themes in 4.7

    Additional User-facing Changes

    With over 90 tickets fixed in the customize component in 4.7, we can’t cover everything here. But, here are a few more highlights:

    Improved Custom Background Properties UI

    #22058 introduces a more comprehensive and more usable custom background properties UI when a custom background is set up. There are now presets to control all of the detailed options at once, and the individual options are presented in a more visual way. Background size and vertical position are also now available as standalone options when using a custom preset.

    Theme developers should update their add_theme_support() calls for custom-background to specify the default size, vertical position, and preset to reflect their default background image CSS. Perhaps the most significant improvement here is the ability for users to easily set up fixed full-screen backgrounds – and the ability for themes to make that behavior default if desired.

    And even more…

    4.7 also:

    • Loads the frontend preview iframe more naturally, eliminating a lot of weirdness with JS running in an unexpected location and ensuring that JS-based routing will work (#30028)
    • Allows the search results page to be previewed, and any forms that use the GET method in general can now be submitted whereas previously they would do nothing when submitted (#20714)
    • Hides edit post links in the customizer by default. Plugins, such as Customize Posts, can restore the links if they make post editing available in the customizer (#38648), although the visible edit shortcuts should generally be used instead.
    • Shows a cursor: not-allowed for mouse users when hovering over external links in the preview, as these can’t be previewed
    • Officially removes support for the customizer in Internet Explorer 8, preventing users of this outdated browser from accessing the customizer at all (#38021)

    Additional Developer-oriented Changes

    Hue-only Color Picker

    #38263 adds a hue-only mode to the Iris color picker, wpColorPicker, and WP_Customize_Color_Control. Built for Twenty Seventeen’s custom colors functionality, the hue-only mode allows users to select a hue and saves the hue degree as a number between 0 and 359. To add a hue-color control:

    $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'colorscheme_hue', array(
    	'mode' => 'hue',
    	'section' => 'colors',
    ) ) );

    As demonstrated in Twenty Seventeen’s custom colors strategy, the hue-selection strategy opens up a whole new world of possibilities for custom color options in themes. Rather than introducing numerous text and background color options and requiring users to adjust them to ensure that adequate color contrast is provided, themes can consolidate their color options into one or more hue pickers. Then, the corresponding use of hsl colors in CSS allows themes to define color patterns where users customize color hues without impacting the lightness of a color option, thereby preserving the designer’s use of proper contrast between text and background colors, and any use of color lightness for visual hierarchy. Check out the implementation in Twenty Seventeen for inspiration (including instant live preview).

    Fix Sections that .cannot-expand

    When creating custom customizer sections that, for example, display an external link but don’t actually expand to show section contents, the cannot-expand class can be added to the section title container to prevent JS events and CSS hover/focus styles from being applied. Be sure to also remove the tabindex="0" from the container if you copy the core code since your custom section shouldn’t be focusable if it can’t expand (and any contained links or buttons would be keyboard-focusable automatically). See #37980 for details.

    Allow Plugins to do Comprehensive Late Validation of Settings

    To account for custom subclasses of WP_Customize_Setting that don’t apply the customize_validate_{{$setting_id}} filter, this filter now will be applied when WP_Customize_Manager::validate_setting_values() is called. This ensures that plugins can add custom validation for every setting. For more, see #37638.


    Huge thanks to the 61 people (and counting) receiving props for the 120+ customize component commits in 4.7 (as of RC2): @westonruter, @celloexpressions, @afercia, @sirbrillig, @ryankienstra, @helen, @ocean90, @melchoyce, @bradyvercher, @folletto, @johnbillion, @delawski, @karmatosed, @georgestephanis, @dlh, @curdin, @valendesigns, @mattwiebe, @michaelarestad, @joemcgill, @sstoqnov, @lgedeon, @mihai2u, @coreymcollins, @stubgo, @utkarshpatel, @desrosj, @odysseygate, @johnregan3, @aaroncampbell, @mapk, @iseulde, @mrahmadawais, @vishalkakadiya, @sayedwp, @hugobaeta, @jonathanbardo, @jorbin, @tristangemus, @deltafactory, @kkoppenhaver, @seancjones, @presskopp, @Mista-Flo, @nikeo, @adamsilverstein, @lukecavanagh, @coffee2code, @peterwilsoncc, @presskopp, @pento, @Kelderic, @sebastian.pisula, @mckernanin, @FolioVision, @MikeHansenMe, @welcher, @cdog, @grapplerulrich, @iamfriendly, @flixos90.


  • Helen Hou-Sandi 8:49 pm on November 30, 2016 Permalink |
    Tags: , dev-notes   

    Starter content for themes in 4.7 

    One of the hardest things for people setting up sites with WordPress for the first time is understanding what themes are and how a given theme can work for you, especially when there’s no content there to visualize. There are also significant gaps between local theme previews, screenshots, and .org previews. Even when there are easy-to-use site customization tools, it is difficult to figure out where to start and what things are going to be like.

    To help users along that path, 4.7 introduces the concept of “starter content” – theme-specific selections of content to help showcase a theme to users and serve as a starting point for further setup of new sites. Starter content works especially well in tandem with visible edit shortcuts, allowing users to not only see what content might work best where within a theme, but from there to be able to jump to building off of that base without having to initially spend time figuring out, say, which widgets areas map where.

    How it works

    Starter content is applied and displayed upon entering the customizer, with no changes appearing on the live site until customizer changes are explicitly saved and published. In 4.7, this initial view of a theme with starter content will only happen for “fresh sites” – new installs that have not yet had any posts, pages, widgets, or customizer settings updated. This state is indicated in the fresh_site option with a value of 1. The current limitation is in line with prioritizing initial site setup for this release, and allows for themes to begin implementing content and ensuring that there is a solid base before introducing more complicated logic and UI to “merge” starter content with existing content in a future release (#38624). That being said, if two themes in a given fresh site both have starter content, if the starter content from the first theme is applied and you make some changes to that starter content, when you switch to the second theme the starter content from that theme will override the starter content from the first theme only for the settings which have not been modified. Also remember that theme mods are always theme-specific, so starter content for theme switches will never be copied.

    Core provides a set of content that themes can select from (technical details below). These include a variety of widgets, pages, and nav menu items (including references for the pages), along with the ability to provide attachments, theme mods, and options. Any included images for attachments need to be from within a theme or plugin folder and cannot be loaded from an external URL. Twenty Seventeen will ship with starter content enabled; there are no plans to add the functionality to past default themes.

    How to use it

    Themes define a subset of core-provided starter content using add_theme_support() – let’s look at a breakdown of how Twenty Seventeen does things. In its setup function hooked to after_setup_theme, we see an array with collections of widgets, posts (pages), attachments, options, theme mods, and nav menus registered as the starter content. The customizer looks for this starter-content at after_setup_theme priority 100, so do make this call at that point or later:

    add_theme_support( 'starter-content', array( /*...*/ ) )


    Each widget area ID corresponds to one sidebar registered by the theme, with the contents of each widget area array being a list of widget “symbols” that reference core-registered widget configurations. Most default widgets are available (archives, calendar, categories, meta, recent-comments, recent-posts, and search), as well as text widgets with business hours (text_business_info) and a short prompt for an “about this site” style blurb (text_about). Themes should place widgets based on what works best in that area – for instance, business info in a footer widget of a business-centric theme, or a nicely styled calendar widget in the sidebar of a blog.

    Custom widgets can also be registered at the time of starter content registration or later filtered in, which will be more likely the case for plugins, as add_theme_support() for starter content will be overridden by any later calls.

    // Custom registration example
    add_theme_support( 'starter-content', array(
    	'widgets' => array(
    		'sidebar-1' => array(
    			'meta_custom' => array( 'meta', array(
    				'title' => 'Pre-hydrated meta widget.',
    			) ),
    // Plugin widget added using filters
    function myprefix_starter_content_add_widget( $content, $config ) {
    	if ( isset( $content['widgets']['sidebar-1'] ) ) {
    		$content['widgets']['sidebar-1']['a_custom_widget'] = array(
    			'my_custom_widget', array(
    				'title' => 'A Special Plugin Widget',
    	return $content;
    add_filter( 'get_theme_starter_content', 'myprefix_starter_content_add_widget', 10, 2 );

    Posts (Pages)

    Like widgets, core provides posts which can be referenced by symbols; all six currently in the core set are pages, but the starter content API can support various post types (including attachments, which are defined and handled separately). The symbols for the core-provided pages as of 4.7 are home, about, contact, blog, news, and homepage-section. The pages references by blog and news are both empty in the content area and are meant to be assigned as the page for posts (detailed with options below). Imported posts can further be used as post IDs when referenced using the symbol of the item within double curly braces, e.g. {{home}} for the static front page option.

    Posts, like widgets, are also easily customizable, either by overriding specific fields for a predefined item or by defining a new custom one entirely. The available fields are post_type, post_title, post_excerpt, post_name (slug), post_content, menu_order, comment_status, thumbnail (featured image ID), and template (page template name, as would be stored in post meta).

    // Overriding/supplementing a predefined item plus a custom definition
    add_theme_support( 'starter-content', array(
    	'posts' => array(
    		'about' => array(
    			// Use a page template with the predefined about page
    			'template' => 'sample-page-template.php',
    		'custom' => array(
    			'post_type' => 'post',
    			'post_title' => 'Custom Post',
    			'thumbnail' => '{{featured-image-logo}}',


    While attachments are post objects, they have special handling due to the sideloading of specified media. Media must be loaded from within the theme or plugin directory – external URLs are currently disallowed for performance reasons. The location of the media, either as a full file path or relative to the theme root, is indicated in the file array item, and some other post fields are available, with post_content mapping to description and post_excerpt to caption. Imported attachments can further be used by using their respective array keys as symbols used within double curly braces, e.g. {{featured-image-logo}} as the featured image (thumbnail) for a post. In the example below, an attachment is specified and used as the featured image for the about page.

    add_theme_support( 'starter-content', array(
    	'attachments' => array(
    		'featured-image-logo' => array(
    			'post_title' => 'Featured Logo',
    			'post_content' => 'Attachment Description',
    			'post_excerpt' => 'Attachment Caption',
    			'file' => 'assets/images/featured-logo.jpg',
    	'posts' => array(
    		'about' => array(
    			// Use the above featured image with the predefined about page
    			'thumbnail' => '{{featured-image-logo}}',

    Nav Menus

    Nav menus are also specially treated post objects. There are essentially two types of nav menu items – custom links, which require a title and url, and object references, which require type, object, and object_id, which can be a {{post}} symbolic reference.

    Options and Theme Mods

    Options and theme mods are more freeform and merely require a match for a name. Symbolic references to imported items are particularly useful here, such as for the page_on_front option and Twenty Seventeen’s multi-section homepage as stored in theme mods. Themes hosted on .org will likely be limited to theme mods and a subset of options; all other developers are encouraged to consider user experience and expectations first.

    What does this mean for themes?

    Core-provided content helps support a consistent preview experience across themes with high quality localized content, helping users understand how WordPress and that theme fit their needs. Theme authors are encouraged to select from core-provided content, but as is always the case with WordPress, starter content still has some flexibility, and will continue to mature as a feature over time.

    While theme review guidelines need to be finalized and documented, it is anticipated that themes being submitted to WordPress.org will be expected to select from core-provided content to promote consistency and to help keep the theme review process from becoming lengthier, with exceptions being made on a case by case basis. Themes being distributed outside of WordPress.org are not subject to the same review process; however, it is recommended that consistent user experiences be the primary consideration in how starter content is chosen and implemented.

    What’s next?

    Testing this feature with your theme or plugin does not require a fresh install every time – you can set the fresh_site option to 1 using the tool of your choice, such as wp-cli or phpMyAdmin. Do note that content merging logic has not been tackled so you may not quite get the exact same effect as a truly fresh install; however, since all of the changes are held in a customizer changeset and are not otherwise live on the site, there is no data loss, unless you save and publish the starter content overrides of course.

    In the future, all sites should be able to live preview new themes in ways that really showcase that theme’s capabilities, whether that’s with no content made yet or with a lot of existing content to work into the preview. This will take a lot of consideration around user expectations for content merging, and should be tackled as its own feature. There are also potentially interesting extensions such as UI for users to select from sets of content or selectively accept/reject staged changes.

    And finally, to best align preview experiences in various places, theme previews on .org should also leverage starter content. Helping hands are needed here – please ping me (@helen) in Slack should you be interested!

    • Luke Cavanagh 8:55 pm on November 30, 2016 Permalink | Log in to Reply

      Thanks for sharing.

    • Madalin Tache 9:05 pm on November 30, 2016 Permalink | Log in to Reply

      That’s a really good idea! Looking forward to it!:)

    • Hardeep Asrani 9:08 pm on November 30, 2016 Permalink | Log in to Reply

      That’s gonna be a game changer for themes. 🙂

    • t-p 11:39 pm on November 30, 2016 Permalink | Log in to Reply

      To be able to live preview new themes sounds awesome 🙂

    • WPDevHQ 11:40 pm on November 30, 2016 Permalink | Log in to Reply

      Awesome news for themes.

      Will this be carried over to WordPress.org theme preview or does that not work as a `fresh_site`?

    • Omaar Osmaan 11:57 pm on November 30, 2016 Permalink | Log in to Reply

      Awesome thank you!

    • evisiontheme 9:21 am on December 1, 2016 Permalink | Log in to Reply

      Really, great idea. Thanks for the sharing it. We look forward it soon.

    • NateWr 9:39 am on December 1, 2016 Permalink | Log in to Reply

      Looks great! I suppose this has been discussed, but is there any plan to support post meta in a more generic fashion? I’m thinking a key for `post_meta` which can itself be an assoc array with a key/value map. This could be useful for previewing data from plugin custom post types which rely more heavily on post meta.

      • Helen Hou-Sandi 3:16 pm on December 1, 2016 Permalink | Log in to Reply

        Untested at the moment, but I believe this is already technically possible, just requires some more hoop jumping at the moment in the form of having to filter it in using get_theme_starter_content as opposed to being able to specify it during initial registration. That is the case for plugins as it is though, so it’s not really that much of a hoop. So to do that, you would want to use a meta_input arg with the definition of that post, the same way post_title can be specified. Can you let me know if it works?

        • NateWr 9:06 pm on December 6, 2016 Permalink | Log in to Reply

          Hey thanks Helen. I missed this reply in my notifications so just seeing it now. I’ll try to give this a go in the next couple weeks and let you know.

    • Mahesh Waghmare 9:51 am on December 1, 2016 Permalink | Log in to Reply

      +1, Its nice enhancement for theme developer.

    • Ahmad Awais 2:57 pm on December 1, 2016 Permalink | Log in to Reply

      Thanks a lot Helen and all the contributors for making this happen. It’s a huge deal for me and my clients.

    • rheinardkorf 11:15 pm on December 5, 2016 Permalink | Log in to Reply

      Love it! Handy for developers and those looking for themes. Nothing more annoying than previewing a theme with current standard content. Great improvement.

    • Armando Duran 12:46 am on December 7, 2016 Permalink | Log in to Reply

      I tried this on an existing install. For a moment I thought that the fresh_site option would be there after upgrading to 4.7 but then I realized that after adding the option manually on the DB, starter content was there!

      love this feature … and the new 4.7 version of course!

    • Volkv 9:50 am on December 7, 2016 Permalink | Log in to Reply

      But it doesnt work right for me. After fresh 4.7 install I got 20/17 theme loaded WITHOUT any starter pre-loaded content – only with default widgets. Starter changes appears ONLY after I click on customizer button.

      Same behavior with my own theme. Is it bug or what am I doing wrong?

      • WebMan Design | Oliver Juhas 9:23 am on December 20, 2016 Permalink | Log in to Reply

        This is actually intentional. Starter content is present in theme customizer only to preview how the theme looks/works with a content in place. Once you save the customizer settings the starter content should by ported into your website and you should actually see it in your pages/posts, widgets,…

    • Mal 11:06 am on December 7, 2016 Permalink | Log in to Reply

      It doesn’t work for me.

      I just installed WordPress 4.7 and put this in the functions.php file:

      function my_setup() {
      	add_theme_support( 'starter-content', array(
      		'options' => array(
      			'test123' => 'test',
      	) );
      add_action( 'after_setup_theme', 'my_setup' );

      The frest_site option was added to the database automatically with value of 1.

      In footer.php when I run var_dump(get_theme_starter_content()); I get the correct result but when I run var_dump(get_option('test123')); right next to it I’m only getting false.

      I tried to debug that but I can’t figure out what this is supposed to do preg_match( '/^{{(?P.+)}}$/', $value, $matches ) in import_theme_starter_content()?

      I also noticed that all arrays need to be serialized which was kind of unexpected:

      add_theme_support( 'starter-content', array(
      	'options' => array(
      		'test123' => 'test',
      		'test1234' => maybe_serialize( array(
      			'something' => 'test',
      		) ),
      ) );
    • WebMan Design | Oliver Juhas 11:14 am on December 18, 2016 Permalink | Log in to Reply


      This is a great feature, thank you! I have successfully tested it with standard one-site WordPress installation. But for some reason it does not work for me on WordPress multisite. So, my question is:

      Does themes starter content work with WordPress network (a multisite) installation?

      Thanks for the answer in advance!

  • David A. Kennedy 12:22 am on November 29, 2016 Permalink |
    Tags: , , dev-notes,   

    Theming with Twenty Seventeen 

    In 4.7, WordPress gets a new default theme: Twenty Seventeen. Like all default themes, it’s easily customizable for users and developers. This post will cover developer features and a few tricks when customizing the theme.

    Of note

    Override enqueued styles and scripts

    With the use of get_theme_file_uri, introduced in 4.7, Twenty Seventeen lets child themes override styles and scripts with ease. For example, if you want to replace the theme’s global.js file, you can do so by including the same file in your child theme in the same path.


    Twenty Seventeen includes a handful of filters, all of which are documented in line in the code.

    Content width

    The value is filterable in the event a child theme needs to change it.

    function childtheme_content_width( $content_width ) {
        if ( twentyseventeen_is_frontpage() ) {
            $content_width = 960;
        return $content_width;
    add_filter( 'twentyseventeen_content_width', 'childtheme_content_width' );

    Custom header settings

    Like past default themes, Twenty Seventeen filters the arguments for add_theme_support( 'custom-header' );. These can be changed in a child theme. Here, we’ll add flex-width to the current args.

    function childtheme_custom_header_args( $args ) {
        $args['flex-width'] = true;
        return $args;
    add_filter( 'twentyseventeen_custom_header_args', 'childtheme_custom_header_args' );

    Header video settings

    The theme changes the default provided by Core, but that can be modified by a child theme. Here, we change the text on the button in a child theme:

    function childtheme_setup() {
        remove_filter( 'header_video_settings', 'twentyseventeen_video_controls' );
    add_action( 'after_setup_theme', 'childtheme_setup' );
    function childtheme_video_controls( $settings ) {
    	$settings['l10n']['play'] = '__( 'Play my awesome video', 'childtheme' );
    	$settings['l10n']['pause'] = '__( 'Pause my awesome video', 'childtheme' );
    	return $settings;
    add_filter( 'header_video_settings', 'childtheme_video_controls' );

    Front page sections

    Twenty Seventeen uses the Customizer to add sections to the front page. These are filterable with the twentyseventeen_front_page_sections filer. They can changed like so:

    function childtheme_front_page_sections() {
    	return 6;
    add_filter( 'twentyseventeen_front_page_sections', 'childtheme_front_page_sections' );

    With 6 being a new number there. In this way, the number of sections can be adjusted in a child theme.


    One of the theme’s most notable behind-the-scenes features, the use of SVGs means better accessibility for icons, they look great on any device and they’re easier to customize.

    First, the list of social link icons is filterable, so child themes can change it.

    function childtheme_social_links_icons( $social_links_icons ) {
        $social_links_icons['mysocialsite.com'] = 'mysocialsite';
        return $social_links_icons;
    add_filter( 'twentyseventeen_social_links_icons', 'childtheme_social_links_icons' );

    All of Twenty Seventeen’s icons are decorative in nature. But if a child theme wanted to include an icon that needed to be described in an accessible way, it can thanks to built-in options.

    These examples are documented in the code itself. However, for example:

    Using a title:

    <?php echo twentyseventeen_get_svg( array( 'icon' => 'arrow-right', 'title' => __( 'This is title', 'childtheme' ) ) ); ?>

    Another example with title and desc (description):

    <?php echo twentyseventeen_get_svg( array( 'icon' => 'arrow-right', 'title' => __( 'This is title', 'childtheme' ), 'desc' => __( 'This is longer desc', 'textdomain' ) ) ); ?>

    For more information on SVG accessibility, see Using ARIA to enhance SVG accessibility.

    Custom Colors

    Like other default themes, this one comes with some color options so you can make the theme your own. Twenty Seventeen uses saturation to create a custom color scheme that will look great. That saturation level can be adjusted, like so:

    function childtheme_custom_colors_saturation() {
    	return 25;
    add_filter( 'twentyseventeen_custom_colors_saturation', 'childtheme_custom_colors_saturation' );

    So the lower the number there, the more muted a color appears, and the higher it is, the more intense a color becomes.

    You can also add new CSS to the existing CSS output for custom colors.

    By adding a filter, child themes can add additional selectors onto the custom color scheme CSS. Like so:

    // Add child theme selectors for color schemes.
    function dynamic_seventeen_custom_colors_css( $css, $hue, $saturation ) {
    	$css .= '
    	.colors-custom .content-menu > article:not(.has-post-thumbnail),
    	.colors-custom .content-menu > section:not(.has-post-thumbnail) {
    		border-top-color: hsl( ' . $hue . ', ' . $saturation . ', 87% ); /* base: #ddd; */
    	return $css;
    add_filter( 'twentyseventeen_custom_colors_css', 'dynamic_seventeen_custom_colors_css', 10, 3 );

    Enjoy customizing Twenty Seventeen and happy theming!

    • djsteveb 1:30 am on November 29, 2016 Permalink | Log in to Reply

      glad to see ” all of which are documented in line in the code.”
      thanks for the tips and early warnings!

      I am sure there will be many that love the video header and many that calculate the waste of this. Without having looking at the code and such, but having some experience with video and wordpress I must ask..

      Is there an option to easily have the video auto play or not play, and instead show a thumbnail with a play button?

      Has someone gotten code to make the video auto-pause when scrolled out of view? I looked hard for this and asked for help in doing that with the flv-player plugin – but never got it working – hopefully others have figured it out by now.

      Is the video going to be self hosted / in the install files for default wordpress or is it hot linked from elsewhere? One way equals bloat for installs, the other sacrifices privacy and puts our page load speed in the hands of third parties.

      Are there options for having the video not load at all in different scenarios like cell phone screen size or 2g data connection?

      Would love to see an option to have a gif (converted to webm perhaps) showing that there is a video to be played – click to download / stream / play – otherwise the bandwidth is saved for the end user.

      Has anyone gotten anything like src set for video yet? Last version of wordpress has some auto magic for different image sizes for different screens right? Does this now work with video?

      One theme I play with has a slider that pulls an mp4 hi rez when screen size is large enough, and then chooses to load a webm version if it detects a smaller screen size – would love to see this (or similar) options in wp core like how images are dealt with.

      anyhow, love to see WP embracing video more by default – it’s great, but comes with some challenges and limitations – that I hope are mostly solved in the future. Also glad to see a focus on having the default themes made with developing in mind for the end users.. I disagree that all default themes are easy to manipulate for end users, certainly 2013 theme and those before were.. the last couple not so much imho.

      thanks to all those who have been and are working on this! the default theme is seriously important for so many reasons!

    • tobifjellner 7:09 am on November 29, 2016 Permalink | Log in to Reply

      Hi. It seems you pasted the same image four times, when attempting to illustrate the saturation setting.

    • Samuel Wood (Otto) 7:41 pm on December 17, 2016 Permalink | Log in to Reply

      Note in your example of removing the parent theme’s filter on “header_video_settings”, you have an order of operations issue.

      Child theme’s functions.php files load and run before parent theme’s functions.php files do. So, in order for a child to remove a filter that is added by a parent, then the remove_filter call should be located in a function that is hooked to after_setup_theme.

      Otherwise, the child will call remove_filter first, before the parent adds that filter in the first place. Which means both filters will be added, and the changes the child is attempting to make will have no effect.

    • i-createweb 12:04 pm on December 29, 2016 Permalink | Log in to Reply

      I am trying to create an image.php file, with corresponding template-part for Twenty Seventeen. I can’t get the image, full size, to appear.

      This is not doing it. I used the content.php code to start with, so I see the title and the comment, footer, header, but no image on the image attachment page.

      Sorry if this is not the correct place to post this, but I was hoping to find this code in this post.

    • i-createweb 8:22 am on December 30, 2016 Permalink | Log in to Reply

      Thanks, Hal-elf! Big fan.

      • i-createweb 8:25 am on December 30, 2016 Permalink | Log in to Reply

        I actually accomplished it. I took code from twentysixteen image.php file and used that. It worked!

        *correction: Half-elf.

    • mattshepherd 9:16 pm on January 5, 2017 Permalink | Log in to Reply

      Assuming I’m a giant idiot and understand almost none of this, is there somewhere I can just straight-up download the proper style.css and functions.php files to make a twentyseventeen child theme?

    • scott9s 3:51 am on January 13, 2017 Permalink | Log in to Reply

      I tried using the content width function, Does it even work?

      I looked through the theme code, and I can’t see it being applied or used anywhere.

    • ShanghaiTimes 1:31 pm on January 13, 2017 Permalink | Log in to Reply

      This is really interesting. Thanks. I’ve been toying about with a child theme here, and finding out a few things that are different than they used to be.

      Can’t locate the fix to remove “Howdy” though.

      Also, probably relating to a comment above, if I copy functions.php into the child directory, my site goes blank? completly.
      Remove function.php from the child directory, and the site comes back.

  • Brady Vercher 10:25 pm on November 26, 2016 Permalink |
    Tags: , custom-header, , dev-notes,   

    Video Headers in 4.7 

    WordPress 4.7 extends the Custom Header feature to introduce support for video.

    Video headers are considered decorative elements — like header images, but with motion. With that in mind, they play automatically, loop by default, and don’t have sound. They work best when paired with an image, so they can progressively enhance the experience when video is supported.

    Header media UI in the customizer when a theme supports video.

    Adding theme support

    Adding support for video headers to a theme requires three basic steps:

    Registering theme support

    Support for video headers can be registered when adding support for custom headers in a theme.

    add_theme_support( 'custom-header', array(
     'video' => true,
    ) );

    Adding support this way does a few things:

    • Renames the “Header Image” customizer section to “Header Media.”
    • Registers customizer controls for selecting a video from the media library or entering a URL to a YouTube video.
    • Enables support for Selective Refresh for header images.

    Displaying the header

    In previous versions of WordPress, generating the image tag manually was the recommended way to display a header image. WordPress 4.4 introduced the_header_image_tag() to take advantage of the responsive image improvements.

    In WordPress 4.7, the_custom_header_markup() unifies support for header images and videos and is the recommended method for displaying custom headers.

    It prints a div that will contain a header image if one is set in the customizer and will also enqueue the wp-custom-header.js script if a video is set in the customizer. The script determines if the environment supports video, and if so, it will progressively enhance the header by replacing the image with a video.

    Styling the play/pause button

    When videos are ready to play, the wp-custom-header.js script inserts a button for pausing and playing the video to help improve accessibility. Core does not apply any CSS to the button in order to make it easier for themes to style. Themes should ensure the button is visible, fits within the design, and add icons if desired.

    Pause Button
    <button type="button" id="wp-custom-header-video-button" class="wp-custom-header-video-button wp-custom-header-video-play">Pause</button>

    Play Button
    <button type="button" id="wp-custom-header-video-button" class="wp-custom-header-video-button wp-custom-header-video-pause">Play</button>

    The text for the button can be modified using the header_video_settings filter.

    Styling custom headers

    When styling custom headers, it’s important to be aware of the various elements that can be used for header media.

    A container div with a wp-custom-header class will always be rendered when a header image or video is available. The div may contain an image, video, or iframe depending on the source of the video, so each of those elements needs to be considered.

    The following selectors should be fairly standard for creating responsive headers:

    .wp-custom-header iframe,
    .wp-custom-header img,
    .wp-custom-header video {
    	display: block;
    	height: auto;
    	max-width: 100%;

    Accessibility considerations

    A button to toggle the play/pause state of the video is automatically rendered to help users who may be distracted or disoriented by motion. Voice assistance is also available using wp.a11y.speak, and like the button text, the strings can be modified using the header_video_settings filter.

    Bandwidth considerations

    To alleviate concerns about bandwidth, videos are only loaded on the front page for viewports that are at least 900 pixels wide and 500 pixels tall. The maximum file size is also capped at 8MB; however, we strongly encourage smaller files be used whenever possible.

    Filtering the front page restriction

    By default, videos are only loaded on the front page and only the header image is shown on other pages calling the_custom_header_markup(). Themes that need to display the header video on pages other than the front page can:

    • Define a custom callback for the video-active-callback header argument.
    • Use the is_header_video_active filter.

    Testing the environment for video support

    Themes may also want to customize the criteria used to determine whether or not a video should be embedded. The header_video_settings filter can be used to modify the minimum viewport width and height.

    On the front end, the wp.customHeader.supportsVideo() method can be redefined. For instance, it might be desirable to test the user agent to prevent videos from loading on mobile devices that don’t support autoplay. As browsers introduce bandwidth APIs, it may also be worthwhile to disable video on devices with limited bandwidth.

    Selective Refresh enabled by default

    When registering support for video headers in a theme, header image settings in the customizer are updated to use the postMessage transport to take advantage of the Selective Refresh API introduced in WordPress 4.5. This ensures header images and videos can be updated in the customizer without refreshing the preview window.

    If the_custom_header_markup() template tag isn’t being used, themes will need to update the custom header partial to use a custom render_callback, or change the transport for the header_image and header_image_data settings back to refresh.

    Creating custom video handlers

    Locally hosted mp4 and mov files, as well as YouTube videos, can be used for video headers by default, but it’s possible to add support for additional sources as well.

    The wp-custom-header.js script exports a wp.customHeader.handlers global variable that contains a list of video handlers. Each handler accepts information about the current video to determine if it can process it, and if so, it creates the video and inserts it into the DOM.

    Core registers two handlers, one for native video, and one for YouTube videos. Each handler extends a base class exposed at wp.customHeader.BaseVideoHandler and implements a basic interface to make sure all videos receive the same level of support.

    In the customizer, there is validation to ensure that local videos are a supported format and file size, and that external video links are to YouTube. This validation needs to be filtered to account for custom handlers, either with the customize_validate_external_header_video and customize_validate_header_video filters to filter the core validation functions, or by changing the validation_callback on the header_video and external_header_video customizer settings. See the documentation on customizer validation for more details.

    For an example of registering a custom video handler in a plugin, take a look at how this plugin registers support for Vimeo.

    New functions and hooks

    • has_header_video() – Checks whether a header video has been set in the customizer.
    • is_header_video_active() – Checks whether a header video is eligible to be shown for the current request.
    • get_header_video_url() – Retrieve the header video URL. May be a local attachment URL or a URL for an external source.
    • the_header_video_url() – Display the header video URL.
    • has_custom_header() – Checks whether a header image or video is set in the customizer and is available for the current request.
    • get_custom_header_markup() – Retrieve the markup for displaying a custom header image (this does not include video support).
    • the_custom_header_markup() – Display the custom header markup and enqueue a script for rendering video in supported environments.


    • is_header_video_active – Whether a header video should be shown for the current request if available.
    • header_video_settings – Settings that are exported to the wp-custom-header.js script during initial page load and when updating the custom header partial in the customizer preview. The default values are:
      • videoUrl – URL for the selected video.
      • mimeType – MIME type of the selected video.
      • posterUrl – URL for the fallback header image.
      • width – Video width.
      • height – Video height.
      • minWidth – Minimum viewport width to embed a video.
      • minHeight – Minimum viewport height to embed a video.
      • l10n – An array of button text and accessibility strings.

    Theme support arguments

    When calling add_theme_support( 'custom-header' ), two new arguments are available:

    • video – Registers support for video headers.
    • video-active-callback – Defines a callback used to determine whether a header video should be shown for the current request. Defaults to is_front_page.
    • Paal Joachim Romdahl 12:15 am on November 29, 2016 Permalink | Log in to Reply

      Thank you for a very good overview!

    • Guido Scialfa 12:36 am on December 2, 2016 Permalink | Log in to Reply

      Probably I’m doing something wrong but the height and width must be set for the custom-header or the frame will not be visible because of the ‘width’ and ‘height’ defined are 0.

      Also, it is right that if i set the header image that is for example 640×480, the video will get the same size? Because even if I set the width and height for the custom-header I get the resolution of the image.

      I’m so sorry, most probably this isn’t the right place to ask for this.

      Anyway, thank you for this new great feature 🙂

    • AH-WebDesign.net 1:06 am on December 7, 2016 Permalink | Log in to Reply

      I’m looking forward to implementing the video header in my theme. Thanks for the detailed documentation.

    • Gioni 3:20 pm on December 7, 2016 Permalink | Log in to Reply

      Yeah, that’s a great feature to reduce conversion rate and increase bounce. I hate those automatically started videos and will never use them in my projects and on my sites. When I see such useless, annoying and resource consuming video on the site I just close it or jump to inner page.

    • tremmal 9:05 am on December 9, 2016 Permalink | Log in to Reply

      Would be nice to implement volume control in header video. Standard volume should be 0, zero, but the user should be able to adjust it.

    • Bonaldi 7:46 pm on December 30, 2016 Permalink | Log in to Reply

      I agree, the user should be able to adjust the volume. Missing.

    • wpweaver 9:18 pm on January 3, 2017 Permalink | Log in to Reply

      I duplicated 2017’s BG parallax header video look, but now I’m going crazy.

      I’d like a video just in the header area – like a traditional wide and tall banner image – but a video (YouTube). Is there a way to make the video size responsively instead of vertical or horizontal letterboxing? If you get the size of the video just right, it will match the corresponding image, but then letterboxes if you resize the page.

      Fitvids does not seem to be able to fix it either.

      As usual with new WP features, there is no really good documentation with real world examples. So far, 2017 seems to be it. It is just so hard to read code to try to figure out what really is going on.

      • wpweaver 1:31 am on January 4, 2017 Permalink | Log in to Reply

        When there’s a video displayed in the header as a replacement for the header, you need to make the .wp-custom-header div position:relative;height:0;padding-bottom:aspect-ratio %; and then make the .wp-custom-header iframe div absolute, top,bottom: 0; height,width:100%.

        The aspect ration % is the width / height (e.g. 9/16 for 56.25%). Getting the aspect ratio % right in the .wp-coustom-header div is critical to avoid black letterbox bars. If the matching image picture has the same aspect ratio as the video, then all is well. Otherwise, you may want to set the height and width with a ‘header_video_settings’ filter to the proper aspect ratio. Note that you don’t really need the real size and width here, just the aspect ratio: 16 for the width, 9 for the height, for example.

    • abain 7:04 pm on January 6, 2017 Permalink | Log in to Reply

      Thank you for the review. Do you know how I can enable audio for a YouTube URL in the Header (for my Front Page)? I understand on Twenty Seventeen the audio is muted by default. I would like to get specific steps on how I can enable the sound. Thanks!

    • danibaba 10:20 pm on January 14, 2017 Permalink | Log in to Reply

      After installing Twenty Seventeen theme on our website, at Costumize -> Media Header section I see this message: “This theme doesn’t support video headers on this page. Navigate to the front page or another page that supports video headers.”
      How is it possible to enable video header support at 2017 or other themes?

  • George Stephanis 8:03 pm on November 26, 2016 Permalink |
    Tags: , , , dev-notes   

    Extending the Custom CSS editor 

    With the Custom CSS project merging into WordPress Core, some of y’all may be looking to extend it and do more advanced stuff.  Maybe you help run an existing plugin (like me) that has already provided a Custom CSS input to WordPress core and you’re now looking to migrate that data over.  Or maybe you want to change how it outputs.  Here’s what I’ve found so far in my work converting Jetpack’s Custom CSS module to be an enhancement layer on top of the Core implementation, providing legacy feature parity.

    Disclaimer: This is just what I’ve found to be useful so far, the Jetpack update is still a work in progress as I write this.

    Data Structure

    Core’s data store is in a Custom Post Type named custom_css, and the CSS is stored in the post_content.  It sets up a new post for each theme’s custom css, and only the active theme’s one is used.  There’s no accounting for parent/child themes — it uses the slug from the current stylesheet (child theme) as the post_name; that is, Custom CSS lookups are indexed by the return value of get_stylesheet().  Core does not yet have have a UI for displaying the revisions for changes to Custom CSS or a way display the saved Custom CSS of inactive themes, but revisions are enabled on the post type, so no data is lost until the revision viewer makes its way into core (or the user activates a plugin that provides similar functionality). Follow #31089 for more on revisions in the customizer, for all settings not just for Custom CSS.

    Getting The Custom CSS

    The generated CSS itself can be gotten via the wp_get_custom_css() function, which just returns the CSS for the current theme as a string. This function is used in the wp_head callback when the CSS is printed into a style tag.  One of the more useful functions in the Core implementation for advanced development is wp_get_custom_css_post( $stylesheet = '' ) — this will return either null or the WP_Post object if the site has any Custom CSS saved for the current site.  If you’re building a custom revision viewer, this will be the post you’ll key off of to fetch the revisions.

    Filters on Read and Update

    The wp_get_custom_css() function applies a wp_get_custom_css filter to the styles just before they’re returned.  This allows for targeted tweaks such as minifying the output on the front-end before it’s echoed by stripping out excess whitespace or the like.  This filter is not meant for a theme or plugin adding styles to the front-end of the site — for that, consider enqueueing your stylesheet normally and adding any dynamic bits via wp_add_inline_style() — this way it will also handle if a child theme or plugin wants to dequeue the parent stylesheet.

    Jetpack has historically provided LESS and Sass (SCSS) preprocessing for our Custom CSS module.  We’re extending the Core implementation via two filters in the WP_Customize_Custom_CSS_Setting class by storing the pre-compiled code in $post->post_content_filtered — so it is versioned correctly, but if the user disables Jetpack, the compiled CSS will still be available in $post->post_content with no data loss for the user.

    When implementing a pre-processor extension to the Custom CSS functionality in core you have to do some swapping between the underlying setting value and the value that gets displayed:

    1. Replace the post_content with the post_content_filtered as the initial setting value via the customize_value_custom_css filter.
    2. Add a wp_get_custom_css filter in the customizer preview (when the customize_preview_init action triggers) to compile the value into CSS just-in-time.
    3. Override the default JavaScript live-preview functionality to instead register a partial for the wp-custom-css style element so that whenever the custom CSS is modified it can be re-compiled on the server and rendered via selective refresh.
    4. When the Custom CSS setting is saved in the customizer, send the saved pre-processed value to post_content_filtered and compile the value to store into post_content.

    For a standalone example of building a pre-processor, see the Custom SCSS Demo plugin on GitHub.


    The Core implementation also is including only very basic sanitization, to the point where it would be dangerous to allow users without unfiltered_html to edit CSS.  If your plugin is adding further sanitization to the saved CSS, you can broaden the user base by remapping the edit_css capability (which Core defaults to unfiltered_html) like so:

    add_filter( 'map_meta_cap', 'mycss_map_meta_cap', 20, 2 );
    function mycss_map_meta_cap( $caps, $cap ) {
      if ( 'edit_css' === $cap ) {
        $caps = array( 'edit_theme_options' );
      return $caps;

    Migrating an Existing option to Core CSS

    Does your plugin or theme have a custom CSS option stored as an option or a theme_mod? Consider migrating content from your custom setting to the core functionality and hiding your custom UI. Here’s a general migration script, which can be located where you see fit in the context of your original code:

    if ( function_exists( 'wp_update_custom_css_post' ) ) {
    	// Migrate any existing theme CSS to the core option added in WordPress 4.7.
    	$css = get_theme_mod( 'custom_theme_css' );
    	if ( $css ) {
    		$core_css = wp_get_custom_css(); // Preserve any CSS already added to the core option.
    		$return = wp_update_custom_css_post( $core_css . $css );
    		if ( ! is_wp_error( $return ) ) {
    			// Remove the old theme_mod, so that the CSS is stored in only one place moving forward.
    			remove_theme_mod( 'custom_theme_css' );
    } else {
    	// Back-compat for WordPress < 4.7.

    I hope some of this has been useful to folks interested in diving deeper into modifying the Core Custom CSS editor.  It’s still somewhat early days for the feature, so please reach out in #core-customize on Slack with any unexpected use cases or concerns!

    • Joy 8:25 pm on November 28, 2016 Permalink | Log in to Reply

      Given that the Custom CSS in core is brand new, and it is output last, the migration code you used:
      `$return = wp_update_custom_css_post( $core_css . $css );`
      probably should be
      `$return = wp_update_custom_css_post( $css . $core_css );`

      • George Stephanis 8:50 pm on November 28, 2016 Permalink | Log in to Reply

        But by that logic, shouldn’t it be core first, as that is what the user has set most recently?

        In practice, it doesn’t make much difference. Most of the time, if things are updated promptly, the Core CSS will be empty as it’s not been used yet.

  • Joe McGill 9:20 pm on November 22, 2016 Permalink |
    Tags: , dev-notes,   

    Media Changes in 4.7 

    This post provides an overview of the changes to the Media component in WordPress 4.7. See a list of all the 4.7 media tickets.

    Two notable changes, enhanced PDF support in the media library and changes to the default fallbacks for alt attributes, are explained in separate posts.

    Enhanced PDF Support in WordPress 4.7

    Improving accessibility of image alternative text in 4.7

    Make media library searchable by file name (#22744)

    Before 4.7, if you uploaded a file to the media library and changed the title, it wasn’t possible to find that file again by searching for the file name. Now, attachment search queries will also include matches to the _wp_attached_file post meta value.

    Other enhancements and bug fixes

    • Added a $wp_error parameter to wp_insert_attachment() (#37813)
    • Fix Drag/Drop Ordering of Media in Chrome on touch enabled devices (#31652)
    • Avoid undefined offset notice in wp_prepare_attachment_for_js() when image_downsize filter in used in (#34437).
    • Improve docs for image_send_to_editor filter (#34823).
    • Use wp_get_attachment_metadata() instead of get_post_meta() where appropriate (#36246).
    • Ensure wp_get_attachment_link() output text for non-images (#37343).
    • Avoid undefined index notices when pathinfo() is used (#37608).
    • Improve alignment of inputs and button heights in media edit screens (#37806).
    • Set focus when closing the media modal (#38142).
  • Mike Schroder 6:12 pm on November 15, 2016 Permalink |
    Tags: , dev-notes,   

    Enhanced PDF Support in WordPress 4.7 

    WordPress 4.7 makes it easier to preview PDFs in the media library by generating image representations of the first page, which are now used throughout the media library and media attachment screens.

    If a WP_Image_Editor is available that supports PDF, the following sizes are generated:

    • Full size representation, rendered at 128dpi.
    • Thumbnail (without cropping)
    • Medium
    • Large

    The sizes generated can be modified, or the feature disabled entirely via the new fallback_intermediate_image_sizes filter, and are all stored in the sizes array in attachment meta.

    The preview images generated are used within the Media screen, Gallery, Attachment Details, and on the Attachment page for PDFs.

    Core support is provided through WP_Image_Editor_Imagick and requires Imagick, ImageMagick, and Ghostscript support. When not supported, or if the generation fails, WordPress falls back to previous behavior and saves the attachment without adding image previews to meta.

    For more context, see #31050 for the primary ticket and #38594 for the filter.


    Since this change requires having Imagick load only the first page of a PDF for performance reasons, this means that if you rely on core loading the entire PDF for your extension of WP_Image_Editor_Imagick, this will no longer function as expected (See: #38832).

    As a result, in [39303], the PDF setup code was moved to WP_Image_Editor_Imagick->pdf_setup(), which can be overridden to restore the previous behavior if needed.

  • Joe McGill 5:40 pm on November 11, 2016 Permalink |
    Tags: , , dev-notes,   

    Improving accessibility of image alternative text in 4.7 

    WordPress 4.7 includes a change to the way image alt attribute values are generated. Formerly, any time WordPress created the markup for an image with an empty alt value, it would attempt to use either the caption text or the image title—in that order—as a fallback value.

    In 4.7, we have removed this fallback behavior.

    To ensure your images having meaningful alternative text, you should make sure to set a value for alt text in your media library.

    How removing fallbacks improves accessibility

    The intent of the fallbacks were to ensure each image included alternative text. In practice however, this fallback behavior often resulted in poor user experiences for people using screen readers. As counterintuitive as that may seem, let’s take a look at some common examples.

    Consider a situation where we’ve uploaded an image named “edbc4ef7.jpg” without changing any additional information. WordPress will generate the image title from the file name as shown in the following screenshot of the insert media modal.

    Attachment details for an image shown in the insert media modal.

    Formerly, inserting this image in a post would result in HTML similar to this (simplified slightly for clarity):

    <img src="https://example.wordpress.org/wp-content/uploads/2016/11/edbc4ef7-1024x683.jpg" alt="edbc4ef7" width="700" height="467" />

    A person using a screenreader on this page would end up hearing the file name read to them, which is not the most helpful experience, and can be quite frustrating when the file name is lengthy.

    For another example, setting a caption value but no alternative text would result in markup that looks something like this:

    <figure id="attachment_1741" style="width: 660px" class="wp-caption alignright">
        <img src="https://example.wordpress.org/wp-content/uploads/2016/11/edbc4ef7-1024x683.jpeg" alt="This is a caption." width="660" height="440">
        <figcaption class="wp-caption-text">This is a caption.</figcaption>

    Notice that the alt value and the figcaption text are redundant? WebAIM describes two ways of presenting alternative text:

    • Within the alt attribute of the img element.
    • Within the context or surroundings of the image itself.

    The same article goes on to explain that an alt attribute value may be omitted when an identical figcaption is present, to avoid redundancy; but best practice when using a figcaption is to provide a separate and different alt attribute to describe that image to users of screen readers.

    In each case, omitting the alt attribute entirely may result in screen readers reading the file name from the src attribute, so WordPress includes an alt attribute with an empty value, i.e. alt="", whenever the alternative text hasn’t been explicitly set—a technique that is common when an image is decorative.

    This change will not affect content already published, but will be the expected behavior for any new content published after upgrading to 4.7. For more background on this issue, see ticket #34635.

    • Carrie Dils 9:52 pm on November 11, 2016 Permalink | Log in to Reply


    • bahia0019 7:48 am on November 12, 2016 Permalink | Log in to Reply

      One thing to bear in mind is that while WebAIM will take either figcaption or alt, search engines haven’t declared the figcaption as a identifier in image search, whereas the alt tag is still in play with Google, et al.

      So, the alt should definitely not be pulled from image file name, but if a caption is filled out, it may be redundant for WebAIM, but it’s not redundant everywhere.

      • Joe McGill 2:51 am on November 13, 2016 Permalink | Log in to Reply

        Thanks for bringing that up @bahia0019. According to Google’s image publishing guidelines, they take several factors into account, including the file name and context around the image, including captions and titles. So it would appear that captions are indeed read by Google.

        Also, to be clear, if you define an alt attribute along with a caption for your images, WordPress will still display both. What has changed is that formerly, including a caption and omitting an alt value would result in the alt attribute duplicating the text that was in your caption.

    • FolioVision 7:21 pm on November 15, 2016 Permalink | Log in to Reply

      Hi Joe,

      Bahia’s quite right in making a difference between what Google says and what Google does.

      One shouldn’t take Google’s guidelines to heart. We coded lots of schema.org into a recipe plugin following Google’s guidelines, passing Google’s structured data tests. That markup was ignored for years, while an older form of microdata actually worked.

      For SEO, we should still be duplicating caption data to alt. It would be even more helpful to include an option to include file names at alt (for those who do use explicit file names), with the option turned off by default as most publishers these days are too lazy and amateur to name their media accurately.

      • Joe McGill 11:07 pm on November 15, 2016 Permalink | Log in to Reply

        Hi @FolioVision,

        Thanks for sharing your experience. I agree that anticipating how Google will actually parse markup in their algorithms is fairly opaque.

        In this case, the changes we have made do nothing to inhibit people from crafting `alt` attributes in ways that optimize how Google ranks their content, if they so choose. At the same time, we are making the experience better for actual users in the process.

        I think the benefits outweigh the downsides for publishers who aren’t taking the time to include good `alt` values with their images.

    • Aaron Jorbin 10:06 pm on November 15, 2016 Permalink | Log in to Reply

      WordPress should always choose the experience that humans have when interacting with a site over an attempt at better search rankings.

      This is a great change. Thanks to all the people who helped make it happen.

    • Chuck Reynolds 9:23 pm on November 16, 2016 Permalink | Log in to Reply


    • blepharisma 8:55 pm on November 21, 2016 Permalink | Log in to Reply

      I think this is just Step #1 — Step #2 would be to prompt the user to enter ALT text when the field is left blank.

      I know that the regulations differ in different countries, but in many is is becoming law that public and private business meet certain accessibility standards. Having the ALT text present is in the first level, and a prompt would go a long way to training content creators to automatically include this very important information.

      In similar implementations, a check box is present if the image is decorative.

    • teamduce 7:43 pm on December 6, 2016 Permalink | Log in to Reply

      Happy to see accessibility continuing to be improved in each release. Keep it up!

    • folletti 1:35 am on December 10, 2016 Permalink | Log in to Reply

      Excuse me!
      But a simple solution when I have used the Title and not Alternative text?

    • Dan 2:18 am on December 28, 2016 Permalink | Log in to Reply

      I always have good alt text, because I always have good titles. But now, I have blank alt text everywhere. This might be helping screenreader users to use sites that are poorly managed, but good sites now have blank images and good authors need to do twice the work (writing a title then copying it into the alt). Thanks!

      Does anyone have a function for restoring the automatic alt?

    • Li-An 11:55 am on December 29, 2016 Permalink | Log in to Reply

  • Nick Halsey 7:18 pm on November 10, 2016 Permalink |
    Tags: , , dev-notes,   

    Visible Edit Shortcuts in the Customizer Preview 

    #27403 added visible edit shortcuts to the customizer preview, making it easier to see which elements of your site are editable in the customizer and how to edit them. Here’s a demo with Twenty Fifteen (note that the ability to toggle icons off has since been removed):

    Implementation: Selective Refresh Partials

    Visible edit shortcuts are an extension of the existing “shift-click-to-edit” functionality built into customizer partials. Partials are sections of the front end of the site, in the customizer preview, that are associated with customizer settings. When settings change, their associated partials are selectively refreshed via an Ajax call without reloading the entire preview. Partials are to the customizer preview what controls are to the customizer editing pane: a visual representation of a setting.

    Buttons are now injected into partials within the preview to expose this relationship visually and to users of all input modes. However, the role of the customizer preview is to provide an accurate representation of the frontend of the site as it’ll appear once changes are published. Accordingly, visible edit shortcuts pose a challenge as they have the potential to significantly hamper the preview-ability of the preview.

    To balance between discoverability and providing an accurate preview, the initial core iteration showed a flash of the buttons when the preview first loads, then hid them. To show the shortcuts, or to toggle them on and off, you could click/tap anywhere in the preview (except on a link or button). Keyboard users had a screen-reader-text button (visible on focus) to toggle the shortcuts on and off. This functionality was removed in [39131] and icons are currently persistently visible when customizing but hidden when the controls are collapsed, and supplemental usability testing validated this decision.

    Background & Prior Implementations

    Shift-click to edit an element in the customizer preview was first implemented with the widget customizer project in WordPress 3.9. Visual approaches to exposing this functionality were explored, but left for a future release. Selective refresh was also first proposed, and put on hold pending development of the concept.

    The first core implementation of selective refresh came with menu management in the customizer in WordPress 4.3. Menus include shift-click-to-edit on a per-menu-item bases, further demonstrating the powerful potential of associating portions of the customizer preview with their associated settings and controls.

    WordPress.com currently supports a similar feature with visible edit icons in the customizer. This approach serves as the inspiration for the final UI being introduced in core, with additional UX adjustments and a complete rewrite of the implementation to make it compatible with as many themes as possible.

    Adding Theme Support

    Theme support for this feature is all about supporting selective refresh, which was added in WordPress 4.5. In some cases, a small amount of additional CSS will be required to ensure that the shortcuts are positioned properly. Edit shortcuts will be enabled by default for all themes, but are contingent on themes supporting selective refresh.

    Selective Refresh for Widgets

    See the post from WordPress 4.5 for adding support for selective refresh for widgets. In most cases, add_theme_support( 'customize-selective-refresh-widgets' ) is the only requirement:

    Implementing Selective Refresh Support for Widgets

    Selective Refresh for Menus

    Menus support selective refresh out of the box unless: a custom nav menu walker is used, the echo argument is false, or wp_nav_menu isn’t used. In those cases, you’ll need to add support directly. Some themes may still be missing full support for selective refresh of menus, which has been enabled by default since WordPress 4.3.  Reference the post for details, but note that it predates the core implementation of an API for selective refresh:

    Fast previewing changes to Menus in the Customizer

    Selective Refresh for Custom Options

    Custom logo (since 4.5) and header video (since 4.7) support selective refresh automatically if you use the core features via add_theme_support. Other core options such as the site title and tagline or header images can support selective refresh if you register partials for them and set their settings’ transport argument to postMessage. Here’s an example from Twenty Fifteen:

    $wp_customize->get_setting( 'blogname' )->transport        = 'postMessage';
    $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
    $wp_customize->selective_refresh->add_partial( 'blogname', array(
    	'selector' => '.site-title a',
    	'render_callback' => 'twentyfifteen_customize_partial_blogname',
    ) );
    $wp_customize->selective_refresh->add_partial( 'blogdescription', array(
    	'selector' => '.site-description',
    	'render_callback' => 'twentyfifteen_customize_partial_blogdescription',
    ) );

    Where the render callbacks call bloginfo( 'name' ); and bloginfo( 'description' ); For more details on adding support for selective refresh for custom theme options, reference the official customizer documentation.

    Support in Default Themes

    Twenty Eleven through Sixteen support selective refresh as of WordPress 4.5, and also support edit icons for most of their features as a result. Twenty Fourteen and Sixteen require a few very minor positioning tweaks to ensure that all of the icons are visible. This is typical of what most themes could expect needing to add.

    Twenty Seventeen will be a great showcase for this new functionality, as the first theme to ship natively with selective refresh support and with visible edit shortcuts. A few additional adjustments in this new theme will ensure that every option can be previewed with selective refresh and provides visible edit shortcuts where appropriate.

    Limitations & Future Iterations

    The biggest limitation of the current approach is that implementation is entirely dependent on themes supporting it. However, unlike with many other theme-supported features, there is no add_theme_support for visible edit shortcuts. Where themes are already using selective refresh, shortcuts will be available out of the box in WordPress 4.7. To add theme support for edit shortcuts, themes need to add theme support for selective refresh, another newer customizer feature that allows the customizer preview to update granularly. Selective refresh provides superior user experience to the default refresh behavior because the preview context is not lost when changes are made.

    Edit shortcuts currently rely on the presence of selective refresh partials for every setting that needs an icon. Some settings may be previewed exclusively with JavaScript via postMessage. Icons also aren’t needed for every option; for example, layout or color options are broader than a specific area of the site, so they aren’t associated with a particular edit icon in the preview. In the future, a structured JavaScript API for partials in the customizer preview could facilitate adding icons to JS-previewed settings that don’t use selective refresh.

    Visible edit shortcuts are also the first step toward exploring the potential to edit elements of a site directly within the customizer preview. For this to be fully investigated, it’s imperative that a majority of themes and customizer option support selective refresh so that areas of the preview are associated with the appropriate customizer settings and so that context-disrupting full page reloads can be minimized.

    Contributors & Call for Help

    @sirbrillig led development of the feature for core based on the equivalent feature on WordPress.com. Core props went to @sirbrillig, @mattwiebe, @celloexpressions, @melchoyce, @westonruter, and @afercia. Thanks to everyone who has contributed so far!

    Now, your help is needed! Here’s what you can do to make this feature shine in WordPress 4.7:

    • Theme authors: add support for selective refresh to your themes. Start with widgets and make sure it’s working for menus, then make sure you’re using the core custom logo feature. Then, add selective refresh to the site title and tagline, header images, and any custom options with associated regions on the frontend.
    • Theme authors: adjust icon positioning in your theme’s CSS. You can add styles to.customize-partial-icon button to adjust all icons, and scope that to a specific container or even .customize-partial-icon-setting_id to adjust a particular edit icon. Note: these were updated with [39136].
    • Everyone: test edit shortcuts with your current theme with WordPress 4.7 Beta 1 (or newer). Most themes should be able to support them on widgets, menus, and logos with minimal effort. Contact your theme’s developer with any bugs or missing edit icon support, refer them to this post, and ask them to add support for visible edit shortcuts.
    • Everyone: test as many themes as possible and look for anywhere the shortcuts don’t display as expected, or at all. Contact the theme author with your findings, refer them to this post, and ask them to improve support for visible edit shortcuts in their themes.
    • Brad Markle 1:58 pm on November 30, 2016 Permalink | Log in to Reply

      Hi Nick! I sure wish you guys had this feature 6 months ago! I did quite a bit of work implementing similar “visible edit shortcuts” in a group of themes I help manage.

      If I need to disable this new feature within the Customizer, is the correct approach to toggle the customize-partial-edit-shortcuts-shown / customize-partial-edit-shortcuts-hidden classes within the body?


      • Brad
    • Luke Cavanagh 10:17 pm on November 30, 2016 Permalink | Log in to Reply

      Solid feature improvement.

    • AJ Clarke (WPExplorer.com) 7:02 am on December 12, 2016 Permalink | Log in to Reply

      I have an issue with the selective refresh icon not working after the theme mod is altered for the first time – https://cl.ly/3A3b1e3S1u12 – when you first load the Customizer you can click the icon and it goes to the correct section but after the partial refresh the icon is not clickable anymore (no errors in the console).

      Is there an argument that can be used using $wp_customize->selective_refresh->add_partial to disable the icon for the specific partial?

      Thanks!! Besides this bug, it is a nice feature!

      To add..doing shift+click on the element always works.

      • AJ
    • AJ Clarke (WPExplorer.com) 7:41 pm on December 29, 2016 Permalink | Log in to Reply

      Yes that fixes it! Thank you so much for the reply Nick.

      Happy Holidays,

    • AJ Clarke (WPExplorer.com) 1:54 am on January 11, 2017 Permalink | Log in to Reply

      I’ve noticed when adding a selective_refresh partial that uses the_content() it always returns empty. You can test it easily by using ‘render_callback’ => ‘the_content’. Is this a limitation of the Customizer done on purpose? Thanks!

    • scamartist26 4:51 pm on January 16, 2017 Permalink | Log in to Reply

      Is there a way to remove these icons? On my personal, and heavily widgetized theme I find it as a big distraction.

    • cramdesign 3:15 pm on January 17, 2017 Permalink | Log in to Reply

      Is there not a way that built in WordPress functions (get_bloginfo, wp_nav_menu, etc) could have selective refresh already baked in?

compose new post
next post/next comment
previous post/previous comment
show/hide comments
go to top
go to login
show/hide help
shift + esc
Skip to toolbar