Underscores wordpress

Underscores (or merely _s as it is also known) is a theme made by Automattic, the company behind WordPress itself. It’s not intended to be a parent theme with which to base any number of child themes on. Instead, the whole point is to hack the code of underscore around to do your exact bidding.

When you’re building sites for a client in WordPress, part of the initial labour is in stripping out all the functionality you don’t need from an existing theme. underscores aims to provide the mere essentials, so you can get on with what makes your site unique. Back in issue 197 we looked at using the Roots WordPress theme (rootstheme.com), and underscores (underscores.me) follows a similar vein.
The whole point is to give you what you do want and none of the niceties that aren’t necessary and end up being stripped away.
In this tutorial we’ll grab the underscores theme, see what goodies it has, and how we can use them to potentially streamline your next WordPress build.


Install WordPress

If your hosting platform has a one-click install for WordPress, that’s usually the fastest and easiest option. Alternatively, upload the latest WordPress files manually, create a database and follow the five-minute install. If you are developing locally, create a new WordPress environment in your local LAMP/MAMP/WAMP stack. A quick shortcut if you have Shell (SSH) access is to download and unzip WordPress directly.

001 mkdir underscores  002 cd underscores  003 wget http://wordpress.org/latest.tar.gz  004 tar xfz latest.tar.gz

Move WordPress into the root

Underscores wordpressWhen WordPress is downloaded, after extraction from the zip file it’s usually in its own WordPress folder. Let’s move the WordPress files into the root of our site’s folder (eg underscores). Either drag and drop through the Desktop or use the command line to move the WordPress files and then delete the empty WordPress folder and source ZIP file. Assuming you are currently in the underscores folder:

001 cd wordpress  002 mv * ../  003 cd ..  004 rm -rf wordpress  005 rm latest.tar.gz

The easy way

While it’s no use if you are cloning underscores direct to a server, when developing locally, the simplest way to create your own personalised version of the WordPress underscores theme is via underscores.me. Just enter your preferred theme naming parameters and it will create a custom ZIP file of underscores with all the files and functions correctly referenced for you.

Download underscores (GitHub)

The quickest way of using the theme on a server is by cloning everything directly from the GitHub repo. Open your command line environment, browse to the site folder and run the following commands. What we are doing is simply moving into the WordPress themes folder, and then copying the underscores theme from GitHub into our themes folder. Once this is all done, we will see a folder called _s in the themes folder.

  001 cd wp-content/themes  002 git clone git://github.com/Automattic/_s.git

Essential changes

If using GitHub to get underscores, it’s necessary before you move on to do a little renaming of the theme. First of all, copy or rename the _s theme folder to something more suitable (we’re using underscores_theme). If you are still at the command line, you can use the command below. Once done, you’ll need to do a theme-wide find and replace. Find _s and replace with: ‘underscores_theme’. Find:_s_ and replace with: underscores_theme_. Find: _s (notice the space before the underscore!) Replace with: underscores_theme (again with a space before). Be sure to use a name that won’t upset PHP functions (eg no hyphens).

001 mv _s underscores_theme

Find and replace

A decent text editor should have a search and replace function that will let the scope be limited to the theme folder. However, if you are happy to use the command line you can also use find and replace there. Here are examples of find and replace commands for renaming references to _s from the OS X command line (substitute references to underscores_theme with your own theme name).

001 find . -type f -print0 | xargs -0 perl -pi -e "s/'_s'/'underscores_theme'/g;"  002 find . -type f -print0 | xargs -0 perl -pi -e "s/_s_/underscores_theme_/g;"  003 find . -type f -print0 | xargs -0 perl -pi -e "s/_sb/Underscores_theme/g;"

Activate Underscores

Underscores wordpress

In the WordPress Admin area, browse to Appearance>Themes and then click Activate under your theme name. Now take a look at the theme in the browser. Spartan indeed! First of all, you might want to amend the reference to the underscores theme in the footer. Open up footer.php in your editor of choice and amend or remove the code to suit.

  001 <?php printf( __( 'Theme: %1$s by   %2$s.', '_underscores_theme' ), '_underscores_  theme', '<a href="http://automattic.com/"   rel="designer">Automattic</a>' ); ?>

Amending style.css

You might also want to amend the text in
style.css to suit the needs of your customised theme design. Besides the WordPress theme information up at the top there, it’s organised with some reset and normalize styles first, and then a few essential styles for things like the navigation, images, entry metadata and the like. Remember that you have to alter the style.css info to suit your new theme.

001 Theme Name: Underscores_theme  002 Theme URI: https://github.com/Automattic/_s  003 Author: Web Designer Magazine  004 Author URI: http://webdesignermag.co.uk/  005 Description: This is a test theme for Web   Designer Magazine based on _s!

Basic layouts

underscores has some very basic layout styles stored in the layouts folder. They are named according to their display. For example, content-sidebar.css should put the main content to the left and the sidebar on the right. For a quick structure, copy and paste the layout that best suits your needs into the bottom of the theme’s style.css file. Keep the comments in so you know where they came from.

001 /*  002 Theme Name: Underscores_theme  003 Layout: Sidebar-Sidebar-Content  004 */  005   006 .site-content {  007    float: right; 008    margin: 0 0 0 -40%;  009    width: 100%;  010 }  011 #content {  012    margin: 0 0 0 40%;  013 }  014 #main .widget-area {  015     float: left;  016     overflow: hidden;  017     width: 20%;  018 }  019 .site-footer {  020     clear: both;  021     width: 100%;  022 }

Add example content

If you don’t have existing content, it can help to have some example content when building up the basic layout. There are a few WordPress plug-ins that do the job; we are adding WP Example Content. From the Admin screen, go to Plugins>Add New and search for WP Example Content. Install and activate the plug-in, then select the WP Example Content menu on the left and choose Add Bundle of Sample Posts.

Create a menu

underscores supports menus, so add one from the WordPress Admin (Appearance>Menus). Name it accordingly (we’d suggest ‘Menu’) and add in links from the left-side. In this instance we have selected all the pages made by the sample content, and nested them accordingly. By default this creates a basic drop-down menu from the nested ul elements, with lots of classes by default to aid styling:

001 <ul>  002    <li id="menu-item-29"><a href="http://  localhost:8888/?page_id=20">Grandchild Page</  a></li>  003 </ul>

Responsive friendly

By default, underscores only adds the width attribute (at 100%) to an image; perfect for responsive designs. Furthermore, the primary menu (that we set in step 11) converts to a menu button below a certain viewport width. By default, this is set to 600px. Amend the js/small-menu.js file in these two places.

001 // Check viewport width on first load.  002    if ( $( window ).width() < 450 )  003        $.fn.smallMenu();  004 // and:  005 if ( browserWidth < 450 )

Template tags

One set of helpers in the underscores theme

is the custom template tags. The file for these can be found at inc/template-tags.php, and it includes
functions for adding classes to things like post metadata, post navigation links, comments, and the like. Just edit the file to suit adding classes where needed for styling purposes. Here, we’re adding a class of article-feedback to comments:

001 <article id="comment-<?php comment_ID(); ?>">

Custom headers

Although not enabled by default, underscores provides a custom header implementation. To enable it, first open the functions.php file and at the bottom of the file is a commented section. Uncomment the following section, save the file and then open inc/custom-header.php.

001 /**  002 * Implement the Custom Header feature  003 */  004 require( get_template_directory() . '/inc/custom-header.php' );

Amending header.php

At the top of the inc/custom-header.php file is a code snippet (starting around line 8). It begins <?php $header_image = get_header_image();. Copy this snippet and open header.php in the root of the theme folder, then copy in that snippet. We added it just after the opening <header id=”masthead” class=”site-header” role=”banner”> tag.

001 <?php $header_image = get_header_image();  002    if ( ! empty( $header_image ) ) { ?>  003        <a href="<?php echo esc_url( home_url(   '/' ) ); ?>" title="<?php echo esc_attr(   get_bloginfo( 'name', 'display' ) ); ?>"   rel="home">  004            <img src="<?php header_image(); ?>"   width="<?php echo get_custom_header()->width;   ?>" height="<?php echo get_custom_header()-  >height; ?>" alt="" />  005        </a>  006    <?php } // if ( ! empty( $header_image ) ) ?>

Including Modernizer

Underscores wordpress

As underscores uses HTML5 markup, it includes the ubiquitous HTML5 shiv for Internet Explorer 9 and below (referenced in the header.php file). However, if you need to provide fallbacks for different browser features you may prefer to include the HTML5 shiv with Modernizr (modernizr.com) instead. Save a version of Modernizr (including the shiv option) to the JS folder and strip this line from header.php:

001 <!--[if lt IE 9]>  002 <script src="<?php echo get_template_  directory_uri(); ?>/js/html5.js" type="text/  javascript"></script>  003 <![endif]-->

Enqueue Modernizr

Open the functions.php file and look for the section commented as Enqueue scripts and styles. Under the existing small-menu section, insert the following code. This loads Modernizr.js and provides a version of 2.6.1 for Modernizr (amend this to suit the version you are using). Note: if supporting IE8 you may want Modernizr to load in the head instead of the footer.

001 wp_enqueue_script( 'modernizr', get_template_directory_uri() . '/js/modernizr.js',   array( 'jquery' ), '2.6.1', true );  

Register the sidebar

Now we have the code to display the output of the sidebar, we need to register it with WordPress. Adding the following code under the previous step will add the sidebar into the Widgets section of the WordPress admin. You can now drag the widget onto a sidebar and see the results.

001 wp_register_  sidebar_widget(  002    ‘author_box_  widget’,          003    ‘Author Box’,            004    ‘your_widget_display’,    005    array(                    006        ‘description’ => ‘Display   information about the blog author in your   sidebar’  007    )  008 );

Enable theme options

There are sample theme options to play with in underscores. Open the functions.php file, browse to the section commented as Custom Theme Options, uncomment the file load section as below and then open the Admin panel and head to Appearance>Theme Options. You’ll see that it ships with a few types (checkbox, text input, select options, radio buttons and a text area).

001 /**  002 * Custom Theme Options  003 */require( get_template_directory() . '/inc/theme-options/theme-options.php' );

Amend Theme Options

To use the theme options, open inc/theme-options/theme-options.php and amend the code to suit the options you want to provide. In this instance, we have amended the text input field to say Disclaimer Title (line 44) and the label (line 186).

001 // line 44  002 add_settings_field( 'sample_text_input', __( 'Disclaimer Title', '_underscores_theme' ), 'underscores_theme_settings_field_sample_text_  input', 'theme_options', 'general' ); 001 // line 186  002 <label for="sample-text-input"><?php _e( 'Disclaimer text input', '_underscores_theme' ); ?></label>

Amend the text area

We also want to amend the text area field, so amend that to suit (lines 47 and 243 respectively). If you don’t want the other options to appear in the Admin


Downloading and Installing _s

You can download _s at underscores.me. The page first offers you a single field: choose the name for your theme. I recommend clicking the “Advanced Options” link and adding a theme slug, author name and website, and description. These values will be added automatically to the theme comments at the top of style.css.

Download Underscores

You’ll be given a .zip file containing your theme files. Upload it to your site using Dashboard -> Appearance -> Themes -> Add New -> Upload Theme, then activate it like normal. Its screenshot is just a checkered pattern. (I asked about uploading your own screenshot.png in the Advanced Options when you generate the theme, but the answer was no.)

Basic Styling

Once you activate _s, the first thing you’ll notice is that it’s the most boring theme you’ve ever seen.

Default Underscores Style

Everything is your basic 16px sans-serif. There are no margins; there’s not much padding; it pretty much just dark gray and blue. And that’s a good thing! This is meant to be simply a base for you to build from, not a client-ready template.

CSS Structure

The style.css file in _s is well-organized and formatted. It breaks down styles into 12 sections:

  1. Reset
  2. Typography
  3. Elements
  4. Forms
  5. Navigation (Links & Menus)
  6. Accessibility
  7. Alignments
  8. Clearings
  9. Widgets
  10. Content (Posts and pages, Asides, & Comments)
  11. Infinite scroll (Optional)
  12. Media (Captions & Galleries)

This makes it easy to start adding your own styles to an already-organized file right away. It also makes it pretty simple to break this file down into several partials if you’d like to use Sass or another CSS pre-processor to maintain your CSS for your custom theme (that’s what I’d do). Or if you prefer, there are some Sass–ready forks of _s available on Github.

Template File Structure

_s carefully follows the WordPress template file naming convention. Your basic template files are index.php, archive.php, page.php, and single.php. These each use the get_template_part() function to call the appropriate partial files (like content-page.php or content-single.php). You’ll also find standard WordPress files like header.php, footer.php, and sidebar.php in _s.

Underscores File Structure

This clean organization system sets a maintainable pattern for developers to follow. If you were to add a custom post type called Staff for a company, you’d create archive-staff.php to display all the Staff and single-staff.php for an individual members. Those pages would call content-staff.php for content. If you need to call different content for archive vs. single, you could use the is_post_type_archive() conditional test inside content-staff.php to serve different versions of the content for different views.


I highly recommend trying _s the next time you need to develop a custom theme from “scratch.” It’s licensed under the GPL, so you’re free to do what you like, including developing commercial themes based on _s. The theme is cleanly coded, meets modern standards, and doesn’t include bloated frameworks or styles.

If you’ve used _s for an awesome theme or have a different blank theme that you love, please let us know in the comments!


In this article I will you through complete steps on how to develop a theme using Underscores. I will explain what files comes with underscores and the code in them. By the end of the tutorial you will learn enough to use underscores for creating a WordPress theme.

Starter Theme vs Theme Framework

Before we get started with Underscores its important to know the difference between a WordPress starter theme and WordPress theme framework.

First of all both are WordPress Themes which can be installed and used like any other theme. Their sole purpose is to provide a foundation for creating a complete theme.

Starter themes aren’t made to be used in production sites as they lack styles and advanced functionality. They just provide the WordPress core theme functionality. They contain nothing more than the basic code that every theme must contain. To develop a theme using starter theme you need to edit/add code and files in the starter theme. Underscores is a starter theme. Therefore it provides only the core WordPress functionality and outputs basic markup for a theme.

Whereas a theme framework is a stand alone theme which can be used in a production site. There are more advanced as they expose functionality other just that WordPress core functionality. For example they have built in SEO, Social Sharing, Social Meta Tags, Theme Options page etc. To create a WordPress theme using theme framework you need to create a child theme which uses the theme framework as a parent theme. And then write/edit code of the child theme with out touching the parent theme(or theme framework). Genesis framework is a theme framework.

Generating a Underscore Starter Theme

To generate a underscores starter theme visit underscores.me and in the input box type a theme name for your theme and click generate button.

You need to provide a theme name while generating the starter theme so that underscores can prefix all the custom functions with the theme name. This is required according to WordPress coding standards.

Creating a Development Environment

You shouldn’t use your production site for theme development. You need to use localhost or an another public server. Make you have installed WordPress and activated the generated underscores theme.

Now import sample data for unit testing the new theme which you are going to create. And also make sure you have installed Monster widget and configured WordPress to display errors/warnings.

You can also make your theme development environment more advanced by installing Theme Check plugin.

Template Hierarchy and Template Tags

Every post, page, attachment have an unique id assigned by WordPress when they are created. Make you make an HTTP request to WordPress, it resolves the URL slug to an id to find the resource type. And then it uses template hierarchy to execute appropriate PHP file to produce response.


Template tags are functions used in theme files to prevent code duplication(for including other PHP files or functions output in the current file) and generate dynamic information.

For example: if you make a request to a post with id 1288 then WordPress executes single.php file. single.php file uses template tags to display output response.

Before you begin with theme development make sure you have good understanding of template hierarchy and all types of template tags.

Theme Information

You need to change theme information such as theme URI, author, description, text domain and tags in the style.css file.

After you have completed theme development take a screenshot your theme and save it as screenshot.png in the theme folder.

Tags directive needs to contains comma separated list of tags which are predefined as Tag Filters in WordPress.org.


When index.php, archive.php or search.php cannot find any post then they include content-none.php file. This file has PHP conditions to display different message in different scenarios.

Multi Langauge

To provide multiple language versions of your theme provide translations of static strings in the already existing “languages” directory. In functions.php file underscores already provides code to load the translations i.e., load_theme_textdomain.

Most of the time you just don’t want to translate the theme and leave it to the theme users to translate it if they want.

In either case you need to wrap the theme’s static strings in __() so that translators can find the static strings in an theme. And if the theme is already translated then this function returns the WordPress locale strings.

functions.php File

functions.php file provides information about your theme to WordPress installations And defines and loads theme functionality.

Almost everything in this file is wrapped with if(!isset(function_name)) so that you can later use this theme as a parent theme for creating a child theme. For example: This can be used to creating a PRO and FREE version of your theme. This condition checks if child theme doesn’t define this function they use parent’s.

Here are some of the functionalities provided by functions.php file.

  • It provides the $content_width which is used by WordPress and Plugins while inserting images in an post/page.
  • Registers a navigation menu named “primary” and user understandable name “Primary Menu”. You can add me more navigation menu if you want.
  • Adds HTML5 theme support which is used by WordPress core to decide weather to output HTML5 markup or not while generating markup for search form, comment form, gallery, caption etc.
  • Adds support for post format. You can extend the supported formats or remove from the list. To design different post formats differently in index.php file create files with name content-post_format_name.php. In index.php underscores loads them appropriately using get_template_part( 'content', get_post_format() ); template tag. But to design them separately in single.php file you need to find post format using get_post_format function and change output accordingly. Underscores adds page format specific classes to posts container element.
  • Registers a widget area named “Sidebar” widget. It also wraps the individual widgets and their titles with custom markup for making designing easier. You can register more widget areas if you like.
  • It provides hook for enqueuing scripts and stylesheets. By default it enqueues style.css file and scripts for comments and navigation.
  • WordPress has a built in feature called as custom header. Enable this if your theme header supports a background image. Activation, custom style, template tag and callback code for this feature needs to be placed in the custom-header.php file. uncomment require/include code of this file. Enabling this will bring up a new control on theme customizer.
  • It includes “inc/template-tags.php” file which provides template tags for posts navigation, post date, post meta data, title for archives, description for archives and many others. While developing a theme if you are creating custom template tags then place them in this file.
  • It includes “inc/extras.php” file which contains code that’s not much important or not required for theme to work but adds extra value. If you are planning to create a theme options page or widgets then place code for it here.
  • It includes “inc/customizer.php” file which contains code for customizing theme using WordPress customizer. You can add more theme customizer options in this file. And you can place theme customizer javascript code in “js/customizer.js” file/
  • It includes “inc/jetpack.php” file which contains code for making the theme compatible with jetpack plugin. I often not include this file. Making a theme compatible with jetpack is a complete different story.
  • By default it comments out code for post thumbnail support. But every theme should display post thumbnails therefore uncomment support for post thumbnails.

content-sidebar.css and sidebar-content.css Files

These two css files are not enqueued by default. If you enqueue content-sidebar.css file then it creates two column layout with content on left and widget area on right similarly sidebar-content.css places widget area on left and content area on right.

These files contain non-responsive CSS for layout styling. Place your layout styles inside them and enqueue accordingly. Add/edit code in these files for making the layout more of what you want.

Here is an image which shows the classes embedded by underscores for styling site layout. There are many other classes too but these are the basic ones and enough to style site layout.

Screen_Shot_2015-02-02_at_1 (2)

style.css File

style.css File provides basic CSS for typography, forms, navigation, widgets, content(content of posts, pages, comments and asides), media elements and other HTML elements.

WordPress text editor adds some classes to user generated markup and style.css contains styles for them too such as alignright and alignleft.

Here are some of the things you need to know to add/edit styles to this file

  • It contains styles for styling all kinds of text formatting tags. It uses px unit for sizing font-size. Typography is not responsive by default but you can make it responsive.
  • Site title, tagline and primary navigation menu are stacked vertically inside <header> tag with class .site-header. Primary navigation menu is responsive by default. On mobile and small screen tablets the navigation menu hides and can be expanded using the toggle element which has class .menu-toggle. You can find the basic CSS code for title, tagline and navigation menu in style.css file and JavaScript code for toggling in “js/navigation.js” file.
  • This file doesn’t contain and CSS to style WordPress default widgets such as search widget, category widget etc. You need to style them too. It also doesn’t contain any code to style widget titles. It just contains basic style for .widget class which wraps individual widgets. By default it hides the WordPress search widget but you can unhide it if you aren’t providing a search box anywhere in your theme.
  • Blockquote selectors blockquote cite and blockquote em are not provided in the file therefore you need to add them and style them too.
  • It provides CSS selectors for styling image captions.
  • WordPress editor can also add gallery of images in an post. These are user generated galleries. This file has basic CSS code to style them. You can add more CSS attributes to make them look even better for your theme. Remember that some images in gallery also come with captions so style accordingly as this file’s gallery selectors ignore them.
  • It contains CSS for styling basic HTML form elements.
  • It contains CSS for styling media elements such as iframe, embed and object.
  • It contains a set of CSS for styling anchor tags of a theme.
  • It contains CSS selectors for styling other HTML elements such as lists, tables etc.
  • It contains CSS selectors for styling sticky posts, post entry meta, post title, post anchors, comment anchors, author comments.

This file is basically divided into three parts: normalize CSS, HTML tags selectors and WordPress/Theme specific selectors. But its still missing not obvious HTML tags and WordPress/Theme selectors.

Featured Image

Underscores doesn’t embed post thumbnails by default to index, post or page. You need to add PHP and HTML markup to generated and display featured images.

Author Page

It doesn’t have author.php file. It default to archive.php file. You need to add author.php file and display author information in it.


Underscores starter theme’s features and code changes very often. Everything I mentioned is correct for the starter theme which was available by the time I was writing this post. I will often edit this article if I will see major changes in underscores.


На днях участники проекта Underscores объявили о том, что тема стала включать в себя поддержку Sass. Популярная стартовая тема Underscores для WordPress – это проект с открытым кодом, поддерживаемый Automattic. Как заявил один из участников проекта, Тэмми Листер, многие пользователи желали увидеть поддержку Sass в Underscores: «сообщество попросило добавить Sass. Поскольку Sass присутствует в ядре, это выглядело целесообразным. В данный момент он уже вплетен в поток операций многих создателей тем».

Если вы посетите сайт Underscores.me и щелкнете по «Advanced Options», вы увидите там новый чекбокс, созданный для включения поддержки Sass.


По словам Тэмми, поддержка Sass включена таким образом, чтобы предоставить разработчикам полную свободу его использования:

«Все люди используют и компилируют Sass для своих целей, поэтому тема _s не должна принуждать кого-либо идти каким-то одним фиксированным путем. В этом смысле, Sass обеспечивает чистый подход, не требуя Compass или каких-либо других скриптов»

Поддержка Sass появилась в результате объединения многочисленных pull request и форков проекта на Github. Однако участники проекта на хотят ограничиваться одним лишь Sass — они открыты и для других препроцессоров CSS. «Мне по-прежнему хотелось бы видеть форк Less для _s. Мы стараемся открыть путь и для других препроцессоров», говорит Листер.

Ранее в этом году WordPress.com формально открыли свой собственный рынок для разработчиков тем. Инструкции по добавлению тем достаточно строги, и разработчикам предлагают использовать тему _s в качестве стартовой точки. Несмотря на то что многим авторам тем полюбилась возможность использования mixin и переменных, использование препроцессора не является обязательным требованием для попадания темы на WordPress.com.

У каждого создателя тем WordPress есть свой уникальный поток операций, который может включать в себя использование препроцессора, и участники проекта Underscores будут отдавать этому уважение. « Тема_s не указывает вам, как нужно делать те или иные вещи, она просто помогает вам начать разработку. Все, что мы добавляем к теме, будет отвечать этому правилу», говорит Листер.

Добавление поддержки Sass – еще один поворотный момент для проекта, наряду с тем, что теперь репозиторий GitHub темы Underscores будет использоваться только для разработки. Если вы хотите использовать Underscores, команда рекомендует вам скачать тему напрямую с сайта Underscores.me.

Источник: wptavern.com


Привет друзья! Я начинаю курс уроков по стартовой теме Underscores или как ее еще называют _s. В своих видео уроках я покажу, как нарисовать шаблон с нуля на WordPress и посадить на стартовую тему Underscores. Преимущества стартовой темы Underscores в скорости разработки и готовой грамотной темой с корректным php кодом, без ошибок, которые может случайно допустить любой разработчик, делая тему для WordPress с полного нуля. На Underscores разработаны стандартные темы WordPress, которые идут в комплекте (twentyfourteen, twentyfifteen, twentysixteen). В первом уроке, мы с вами нарисуем полностью готовый дизайн в фотошопе, а в следующих уроках перейдем к верстке/натяжке дизайна на Underscores. Под видео вы найдете ссылку на bootstrap сетку для фотошопа, готовый дизайн урока и горячие клавиши, использованные в фотошопе.

Скачать bootstrap сетку для фотошопа: https://yadi.sk/d/pqF1Cyb2qvn3M
Скачать готовый дизайн для wordpress: https://yadi.sk/d/gC24X9yRrWGBT

Горячие клавиши в фотошопе использованные в уроке:

1. Перемещение по холсту — пробел + ЛКВ (левая клавиша мыши).
2. Увеличить/отдалить холст ALT + колесико мыши.
3. Масштаб 100% CTRL + ALT + 0.
4. Включить/отключить клетки CTRL + » (или на русском буква «э»).
5. Включить направляющие сетки GUIDE GIUDE, если включена CTRL + : (или на русском буква «ж»).
6. Склонировать объект CTRL + J.
7. Сгруппировать объект CTRL + G.
8. Включить линейку CTRL + R.
9. Выбрать инструмент текст. Клавиша T.
10. Выбрать Rectangle Tool. Клавиша U.
11. Выбрать инструмент перемещения. Клавиша V.
12. Трансформация объекта CTRL + T. Объект должен быть выделен.
13. Перетаскивание объекта с помощью точек. Клавиша A. Объект должен быть выделен.
14. Поднять слой в самый вверх CTRL + SHIFT + } (или буква «Ъ» на русском).
15. Опустить слой в самый низ CTRL + SHIFT + { (или буква «Х» на русском).

Ставьте лайки, делайте перепосты, если видео было полезно.


Если вы решили заняться разработкой тем для WordPress, то вам не обязательно каждый раз начинать с чистого листа. Стартовая тема _s (Underscores) поможет сэкономить время при разработке новых тем для WordPress.

Тема _s или Underscores (произносится «андерскорс») разработана сотрудниками компании Automattic. Цель данной темы — облегчить и ускорить разработку новых тем для директории WordPress.org и сети WordPress.com. Именно поэтому тема называется «стартовой» и не имеет никакого дизайна:

Сама по себе тема с таким внешним видом бесполезна, потому ее и не выложили в официальную директорию WordPress.org. Но если взглянуть на исходный код темы, то мы увидим хорошую основу для разработки новой темы:

  • Чистая разметка HTML5 со всеми требуемыми шаблонами, тегами и функциями
  • Поддержка произвольных изображений в заголовке
  • Дополнительные функции для пагинации, вывода мета-данных и другие
  • Поддержка изменения значений с помощью postMessage в конфигураторе тем WordPress
  • Поддержка модуля бесконечного скрола плагина Jetpack
  • Готовое подключение языковых пакетов и файл .pot
  • Поддержка навигационного меню, форматов записей и виджетов

Таким образом, чтобы создать новую тему на базе Underscores нам необходимо лишь скачать _s, переименовать ее и придать требуемый внешний вид. Лишний функционал можно легко убрать, а требуемый добавить.

Большинство тем на базе _s ограничиваются изменением лишь CSS файла, но сама стартовая тема рекомендует так же изменять разметку и функционал, если есть необходимость, а про обновления можно не беспокоиться. Это главное отличие стартовой темы от родительской.

Для темы Underscores был также разработан специальный генератор, который облегчает процесс переименования темы, ведь заменить необходимо не только название самой темы, но и все ее функции, текстовый домен, префиксы в названиях опций и другое.

По последним данным генератором Underscores.me воспользовались более 162,000 раз за последние два года, более 30,000 просмотров сайта Underscores.me ежемесячно, 12,000 просмотров проекта на GitHub каждую неделю, более 500 изменений в репозиторий _s, 63 участника в разработке и более 400 пул-реквестов на GitHub.

Есть масса примеров тем основанных на _s, включая стандартную тему WordPress Twenty Fourteen и большинство всех тем от Automattic. Стоит также отметить, что темы разработанные авторами журнала WP Magazine Expound и Semicolon тоже основаны на стартовой теме Underscores.

Лицензия стартовой темы — GPL, а это значит, что при распространении темы основанной на _s автор обязан унаследовать лицензию. Это не значит, что вы не можете продавать темы созданные с помощью Underscores. Есть ряд примеров коммерческих тем созданных с помощью _s.


Что заложено в Underscores

В исходном коде темы изначально заложена хорошая основа для разработки новой темы:

  • чистая разметка HTML5 со всеми требуемыми шаблонами, тегами и функциями;
  • поддержка произвольных изображений в заголовке;
  • дополнительные функции для пагинации, вывода мета-данных и другие;
  • поддержка изменения значений с помощью postMessage в конфигураторе тем WordPress;
  • поддержка модуля бесконечного скрола плагина Jetpack;
  • готовое подключение языковых пакетов и файл .pot;
  • поддержка навигационного меню, форматов записей и виджетов.

Как создать свою тему

Чтобы создать новую тему на базе Underscores, необходимо лишь скачать _s, переименовать ее и придать требуемый внешний вид. Лишний функционал можно легко убрать, а требуемый добавить.

Для темы Underscores был также разработан специальный генератор underscores.me, который облегчает процесс переименования темы, ведь заменить необходимо не только название самой темы, но и все ее функции, текстовый домен, префиксы в названиях опций и другое.

Underscores wordpress
Underscores.me: генератор тем на основе _s

В чем отличие стартовой темы от родительской

Большинство тем на базе _s ограничиваются изменением лишь CSS файла, но сама стартовая тема рекомендует так же изменять разметку и функционал, если есть необходимость.

А про обновления можно не беспокоиться. Это главное отличие стартовой темы от родительской.


Why Underscores (_s) ?

You must have this question in mind that why you should use underscores, so let me explain. However you have bunch of different ways to develop a WordPress theme, but the main reason of using _S as a base theme is that:

  • It gives you a 1000-HOUR HEAD START.
  • It’s open-source 100% GPL.
  • Always up-to-date with the latest WordPress code standards having around 95 contributors on github.
  • Includes well-commented, modern HTML5 templates.
  • It’s not bloated with any CSS framework, options framework, JavaScript library.

Still not convinced? Lets see who is using underscores:

  • Twenty Fourteen theme.
  • All free theme and all premium theme by Automattic launched on WordPress.com in the last two years.
  • And thousands of websites are built over it.

I hope you are now ready to start with WordPress theme development using Underscores. Lets start!

How to build a WordPress theme with Underscores (_S)

The steps would be as follows:

  • Setup your WordPress development environment.
  • Generate a fresh _s theme, install & activate it.
  • Underscores Theme file structure overview.
  • Adding CSS styling & Customizing Theme Files. (Covered in Part 2)

Setup your WordPress development environment

There are already many tutorials available for this, so I won’t cover this in my tutorial however I am referring some good ones here:

  • Setting up a Development environment from WordPress Theme Handbook
  • Guide on setting up MAMP
  • Guide on setting up XAMP
  • Guide on setting up WAMP
  • Guide on how to set up Desktop Server
  • Using Vagrant – Advance Setup

So you are free to whatever option you like to use for setting up your development environment, you can also google for more tutorials if you do not find the above mentioned tutorials useful.

You are also free to directly work on a live server if you like, however developing on a local server is always preferred and speeds up the whole development time.

Generate a fresh _s theme, install & activate it

Now i assume you have set up your development environment and installed a fresh WordPress on it. Now lets head over to the underscores home page and click on the “Advanced Options” link.


Now fill in all your details in the input fields and tick the checkbox also and than click the GENERATE Button.


Now you should have a zip folder containing your new custom _s theme. Install it to your new local (or live) WordPress installation and activate it.

A quick video on how to upload & activate WordPress theme:

Now as you have activated your new theme if you will view your website from front-end it will look like a little messy to you at first, but don’t worry this is the plus point of this base theme as stated above, it’s a blank theme with very little base CSS and is not bloated with any useless stuff itself and therefore is like an empty glass which we can fill with whatever we like.


So the next part would be customizing our new theme as per our new web design. For our example we actually got inspired by the new design of Chris Lema and tried to make our blog theme similar. Here i want to make it clear that we did not clone it exactly, neither we copy any of the code or graphic from his website, we just got inspiration from his blog and this is purely legit (in our opinion at-least). Also let me point down that his website is built over rainmaker platform & the theme / framework used is Genesis Themes. This will be covered in part 2.

Underscores Theme file structure overview:

underscores-filesLets explore the files comes with the underscore themes. Do not get scared with the number of files it has, they are well organize as per the standards of WordPress and well coded obviously.

Files in Root

As you can see in the screenshot most of the files are self-explanatory by names. Lets understand what file does what by understanding the structure of a website.

As you may know the website could be structured with following files:

  • Header
  • Footer
  • Content Section
  • Sidebar

As illustrated in bellow diagram, the basic structure of a website with the theme files mentioned. The header is controlled by the file “header.php”, sidebarby file “sidebar.php” and footer by file “footer.php”.

You may notice that i skipped about mentioning Content Section, this part basically is bit tricky but we have it covered very well by Template Hierarchy.


Now lets understand what files used for generating the content section of a WordPress website. The Content section of a website is dynamic, which means it changes from page to page, and thus uses specific files based on the type of WordPress page is being loaded.

The default file for content section is “index.php“, WordPress uses this as the last file in your theme. However it first look your theme for other specific files by name and use it instead of “index.php”.

WordPress Posts

This refers to a Single Post, for this WordPress uses file”single.php” if available for generating the Content Section. However in Underscores theme this file only provides the structure mainly and includes another file in the “template-parts” directory named “content-single.php“. Which displays the single post content, thus if a WordPress post is loaded those 2 files are responsible for generating Content Section’s content.

WordPress Pages

Now if a WordPress page is loaded, the file “page.php” is being loaded (if available) and again this file also includes another file in the “template-parts” directory called “content-page.php” which displays the content of a page.

Read more about Posts VS Pages. If you are confused !

Archives, Search Results, and Error Pages

Beside the Posts & Pages there are other type of WordPress pages as well, lets look at them as a list with files classification:

  • Archive Pages, Files (archive.php, content.php). This may further classify as: 
    • Category Archive Pages
    • Tag Archive Pages
    • Date Archive Pages
    • Author Archive Pages
  • Search Result Page, Files (search.php, content-search.php)
  • Error Page, Files (404.php)

Default File

As mentioned above the default theme file is “index.php” and if any of the above files will be missing from your WordPress theme (however underscores has all those files) the default index file will be loaded in place of it.

Thus now you should be clear how the files in Underscores theme are structured as per WordPress standards. And Understand the theme structure very well, lets revise the above diagram here as follows:



The above completes the entire structure of any kind of WordPress page, however if you look into the underscores theme folder you will notice more files as well, lets have a look at them.

Comment File

In root there is a file “comments.php” which is responsible for the WordPress comments functionality. It makes the comments display, pings & displays comments form on a WordPress post or page. This is being included in “single.php” & “page.php” files.

Functions File

This is an important file as well in a WordPress theme and WordPress looks for it in a theme root. It is used to setup theme functionality mainly.  Underscores includes a lot of useful and necessary functionality already in functions.php file, such as:

  • Make theme available for translation.
  • Enable support for Post Thumbnails on posts and pages.
  • Primary Menu Registration.
  • Enable support for Post Formats.
  • Custom background feature.
  • Register widget areas.
  • Enqueue scripts and styles.
  • Custom Header feature.
  • more…

Stylesheet File

There is also stylesheet files in a WordPress theme. Underscores comes with a “style.css” file which contains the very basic css to give you a foundation to further style your theme/website. There is also another stylesheet file you can see which is “rtl.css” which is an RTL (right to left) stylesheet. This is being used for right to left languages such as (urdu, arabic, etc).

Screenshot File

There is also a file called “screenshot.png” which is an image file and uses at different spots such as theme’s section in WordPress. Underscores includes a blank screenshot file, however you may update it to your theme’s screenshot.

More Files & Directories

Underscore includes some more files and organized in some directories. However there is no restriction of using the same directories, but Underscores uses them for the sake of better files organization.

“inc” directory:

This contains some PHP files which are to extend the functions.php file mainly.  Files included are:

  • custom-header.php
  • customizer.php
  • extras.php
  • jetpack.php
  • template-tags.php

“js” directory:

As name defines it includes some javascript files:

  • customizer.js
  • navigation.js
  • skip-link-focus-fix.js

“languages” directory:

If you are willing to make your theme translatable to other languages, than this is the directory to provide necessary files.  Underscores already include a “.pot” file.

“layouts” directory:

This contains 2 stylesheet files:

  • content-sidebar.css
  • sidebar-content.css

As the above structure diagrams shows a 2 column layout with the content section column on left & sidebar column on right. However it depends on your project you may want to change the layout to a left column sidebar (sidebar-content) so these 2 files can help you achieve either layout.

“sass” directory (optional):

If you are a sass user and have ticked the checkbox which says “_sassify!” at the time og generating the new underscores theme. Than you will have this additional directory in your theme. Which contains all the sass files for your theme.

“template-parts” directory:

Lastly we have this directory which is being in discussion above which contains some PHP files for content section.

  • content.php
  • content-none.php
  • content-page.php
  • content-search.php
  • content-single.php

What’s next

Now that you have a detailed understanding with the underscores theme and you have installed a blank theme. However this still looks blank. Now in the next tutorial i will walk you through the process of how we customized the underscores theme to make our CakeWP blog website. That will help you dig deep into custom theme development using underscores.

Stay tuned & Subscribe us to get notified as soon the part 2 gets published!


You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.