How To Make Your Theme Multilingual and WooCommerce Compatible

Matt Mullenweg, who is the co-founder of WordPress and the CEO of Automattic, was interviewed by Josh Janssen, where he stated that in May of this year the non-English downloads of WordPress for the first time exceeded the English downloads.

This trend continues with WordPress 4.0 which makes localized WordPress sites so much easier to install and maintain. WordPress 4.0 now gives you the ability to download WordPress in the language of your choice. This will make the installation process a breeze for non-English speakers. In previous WordPress versions, English was the default and other languages were treated as exceptions. WordPress 4.0 makes all languages equally accessible. This change will surely make WordPress even more popular around the world.

The goal of these new features in WordPress 4.0 is to bring an increase in the number of international users of WordPress, who were previously unable to use WordPress due to the language difficulties. What’s more is the Asia-Pacific countries like China, Japan, India, South Korea, and Indonesia are projected to overtake North America in Business-to-Consumer eCommerce sales, according to eMarketer.

What does that mean for you as a theme or plugin developer? First, it means that your product must be ready for localization. All texts have to be wrapped in `gettext` calls, allowing users to run it in other languages; however, internationalization is only the first step. In many countries, being able to run a site in only one language is a major limitation. To truly go global and tap into the huge potential outside of the English-speaking market, your products should also be multilingual-ready.

Fortunately, with WPML, running multilingual sites is easy. We will outline the top seven best practices to follow, so that your themes and plugins work great on both single-language and multilingual sites. By following these simple guidelines and sticking with clean coding, your products can power multilingual sites.

How End-Users Will Translate and What You Need To Be Prepared For

When you develop your theme, it’s critically important to understand how your end-users will translate their sites. Once you realize their perspective, you will realize what you need to do to make your theme multilingual-ready.

A typical theme displays a header, footer, menus, widgets, content and your own custom elements. Here is an example a WooCommerce site, based on a modified Twentyfourteen theme:

WPML descriptionJPGWPML post descriptionJPG

WPML allows you to translate all the standard WordPress elements. This includes:

  • Menus

  • Standard widgets

  • Navigation elements

  • All texts wrapped in `gettext` calls

  • Post content including custom fields and taxonomy

  • Products

  • Theme options

  • Images and strings related to them

You don’t need to add anything in your code to allow all these sections to be translated. Be sure to pay attention to your custom elements, so that your users can translate them, too.

Below is a table, that summarizes how the end-user will translate standard site-elements with WPML. 

What End-Users Can Translate using WPML

Translate the header using WPML String Translation Tool

Since it’s not part of
any post, page or taxonomy, we need to use WPML’s String Translation
to translate it. Go to WPML->String Translation, search for the string by
its content (the title of the site) and translate.

 title of siteJPG

title of site using string translationjpg

Translate WordPress menus

When you go to
Appearance> Menus, you will see WPML’s menu translation controls. Learn
more about translating menus
to see how this works.

Main MenuJPG

Translate Custom Theme or Plugin Elements

Many themes or plugin
have unique features, that store texts in the wp_options table. The Introductory
Message
, by Resort does that exactly.  The theme or plugin
saves these texts in the wp_options table and we need to tell WPML to
translate them. We add this information to the Language Configuration File. There, we tell WPML which entries in the wp_options
table require translation.

This technique is good
when the keys the options are fixed (like in most themes). If your theme uses
arrays of entries, which may grow with user input, you need to register these
entries dynamically. Use WPML’s icl_register_string and icl_t functions to do
this.

Custom headerjpg

Translating the Post Body

WPML lets users
translate content with ease. The post-edit screens include WPML’s
translation
controls, allowing to create new translations and edit
existing ones.

You don’t need to do
anything in the theme or plugin to make this happen. Translating content is a
core feature of WPML.

What you do need to
check is that any text that your theme adds to the output is translatable.

If you’re new to using
GetText, learn more about it in our theme
texts translation FAQ
.

Post Edit ScreenJPG

Translate Widgets with String Translation

WPML lets users
translate the content of text widgets. It also translates titles of all other
widgets. If your theme or plugin creates its own custom widgets, make sure
that you pass their titles through the standard WordPress filters. This way,
WPML will allow users to translate the titles of your widgets via the String
Translation screen.

Widgets ESJPGWidget editingJPG

Translating the Footer

 Some themes have a
custom admin screen to store the footer texts. Like other texts that we saw,
the theme or plugin saved the footer texts in the wp_options table
too. We will add these entries to the language configuration file, telling WPML to translate them.

custom footerjpg  

For a full detailed explanation on how end-users will use WPML visit our Tutorial on Achieving Compatibility with WPML.

You do not have to rewrite your entire theme or plugin because WPML handles all of this.  This tutorial is not as hard as climbing Mount Everest, but there are a few things that you will need to edit in order to make it easy for your end-user.

Now that we’ve covered how people will translate the standard WordPress elements, let’s review together what you should do to ensure multilingual-compatibility for your custom elements.

The Top 7 Best Practices To Make Your Theme Multilingual and WooCommerce Compatible

1. Add GetText Functions to Hard-Coded Text

For plugins or themes, be sure to wrap your hard-coded text in `gettext` functions. This includes the header, footer, and widget text. Your template files display an assortment of product information and hard coded text. For example, most templates will include the product name and a ‘buy’ link. The product name comes from the database, so you don’t need to worry about translating it.

You should make sure that all hard-coded texts are translatable, using `gettext` functions.

Good

Bad

<p><?php _e(‘Similar products:’, ‘my-textdomain’) ?></p>

<input type=”button” name=”buy-button” value=”<?php esc_attr_e(‘Buy now!’, ‘my-textdomain’) ?>” />

<p><?php echo ‘Similar products:’; ?></p>

<input type=”button” name=”buy-button” value=”Buy now!” />

“Similar products” and “Buy now!” are not wrapped in GetText calls.

Make sure that you use your theme’s textdomain for all GetText calls.

2. Use API Functions to Link to WooCommerce Pages

Many e-commerce themes include special pages, like the ‘cart’ or ‘account’. The theme often includes links to these pages, appearing on every page on the site.

If you use a WordPress menu for these links, you should be all set. WPML displays a different WordPress menu for each language, so the links to these ‘special page’ will be different, per language. However, if you hardcode these links in template files, you need to allow WPML to replace the links, with links to these pages in the right language.

The right way to link to the special WooCommerce pages is by using the WordPress API functions and the WooCommerce page IDs. WooCommerce Multilingual filters calls to `get_option()` with the WooCommerce page IDs. It will return the ID of the page in the current language.

Good

Bad

<a href=”<?php echo get_permalink(get_option(‘woocommerce_shop_page_id’)) ?>”><?php _e(‘Shop page’, ‘my-textdomain’) ?></a>

<a href=”<?php echo get_permalink(wc_get_page_id(‘shop’)) ?>”><?php _e(‘Shop page’, ‘my-textdomain’) ?></a>

‘shop’ is the slug of the page in the default language.

<a href=”<?php echo get_permalink(5) ?>”><?php _e(‘Shop page’, ‘my-textdomain’) ?></a>

The ‘shop page’ ID is hard coded. It will be different for different sites and for different languages.

<a href=”/shop”><?php _e(‘Shop page’, ‘my-textdomain’) ?></a>

The ‘shop page’ URL is hard coded. It will be different for different languages.

3. Add Multilingual-Ready Product Listings

If you use the WooCommerce shortcodes to display the product listing, you are all set. WooCommerce will load the products in the correct language and display them.

If you prefer to load products manually, using your own code, make sure that you are using the WordPress API, or WooCommerce API calls. If you access the database directly, WPML will not filter your call and you will get a mix of all of the products in all languages.

Good

Bad

[featured_products per_page=”12″ columns=”4″]

[product id=”99″]

(more)

<?php $products = get_posts(array(‘post_type’ => ‘product’, ‘suppress_filters’ => 0)); ?>

<?php

$args = array(

‘post_type’ => ‘product’,

‘posts_per_page’ => 10,

);

$products = new WP_Query( $args );

?>

<?php $products = get_posts(array(‘post_type’ => ‘product’)); ?>

suppress_filters will be set to true by default, preventing language filtering.

$products = $wpdb->get_results($wpdb->prepare(“SELECT * FROM {$wpdb->posts} WHERE post_type=’product’ ORDER BY ID DESC LIMIT %d”, 10));

WPML doesn’t filter low-level SQL queries. All products in all languages will be returned.

Once you’ve loaded the right products, you don’t need to worry about languages when displaying them. Each product will come with its own custom fields, with information in the correct language.

4. Add Multi-Currency Payment Options

Some global eCommerce sites need both multiple languages and multiple currencies. Your theme should support those sites that require multi-currency. For many non-American sites, supporting multiple currencies is a very important feature. For example, many European sites will need to charge in Euros, British Pounds and US Dollars. Eastern European sites often require Russian ruble and Asian sites need a variety of different other currencies.

Currency SwitcherJPG

Multi-currency support is included in WooCommerce Multilingual. To allow visitors to switch between currencies, your theme should include an optional currency switcher.

You can display a currency switcher, either using a PHP call or by inserting a shortcode.

<?php do_action(‘currency_switcher’, array(‘format’ => ‘%name (%symbol)’)); ?>

[currency_switcher]

For a full tutorial, visit the tutorial on Multi-Currency for WooCommerce. Keep in mind that the currency switcher will only display if the site uses multiple currencies.

5. Become RTL Compatible

English – LTR

Hebrew – RTL

English LTRJPG

Hebrew RTL2JPG

WooCommerce themes must follow the RTL guidelines, just like WordPress themes. You should create an `rtl.css` file, with the CSS rules for RTL display.

Create a new `rtl.css` file and put it in your theme’s root directory. The ‘dir’ direction in CSS will do most of the work and you only need to patch a few places. For RTL languages, set the ‘direction’ attribute in CSS to ‘rtl’.  Additionally add the ‘unicode-bidi- attribute.

Good RTL display added to .body selector:

{

direction:rtl;

unicode-bidi:embed;

}

Now your theme will display in RTL.  To handle exceptions go to the RTL Themes Support Guidelines.

6. Manage Different Text Lengths in Different Languages

When you create your multilingual ready WooCommerce theme, understand that some texts will be longer in certain languages and shorter in others. Some language lengths, you cannot test, because your end-users will translate the content on their own.

For example, look at these two product blocks.

Default LanguageJPG

CSS Optimized for Short Text in English

Different LanguageJPG

Longer Spanish Text Doesn’t Fit the Space

The best way to achieve multiple length compatibility is to test your theme with texts that are x2 longer and ½ shorter. In most cases, this will cover any language that is translated. It is highly recommended to use fluid layouts to handle text of different sizes. A fluid layout will allow each element to resize and capture the area that is needed. Achieving a fluid layout takes time, but prevents visual glitches.

Style definitionJPG

Text Overflows Seamlessly onto the Next Line with No Display Glitch

WooCommerce `style.css` uses the designation `white-space: no-wrap`.  But in our example, in order to wrap the text properly you must use `white-space: normal;`.

7. Create a Language Configuration File

To make your theme fully WPML compatible, you should make it simple for others to run multilingual sites with the theme by creating a language configuration file.

WPML can read a configuration file that details what should be translated in the theme or plugin.  Create and name the file `wpml-config.xml`.  Save the file in the theme’s root directory.  Use the structure and section layout in the example in this wpml-config.zip sample file and edit it with your own custom content.

The content in the `wpml-config.xml` file must be wrapped in the following <wpml-config> opening and closing tags:

<wpml-config>

</wpml-config>

In the `wpml-config` file you set which features need to be translated by WPML, your custom post types, custom taxonomies, custom fields, and admin text (string coming from wp_options), and you can also set the way your theme’s language switcher will look just follow this short tutorial for full examples and details on structuring your language configuration file visit our Language Configuration File Tutorial.

Test Your Site

Now that you understand the need to make your theme or plugin multilingual and WooCommerce ready, and after following customary development practices as outlined above, it is time to test your theme or plugin.

Usually when you test, you would attempt to translate everything by putting in dummy translations in every area of your site.  But this would take a lot of time. Therefore, we have created a Testing tool for you: WPML Compatibility Test Tools Plugin.

This tool will inject dummy translations for your site, so you can switch languages,  and see what got translated, and what stayed in your original language. Our testing tool will save you several hours of testing and will help you see what areas you need to improve in your theme or plugin.

Install the Right Plugins for Multilingual WooCommerce

Your clients will need to have the following plugins for multilingual e-commerce sites with WooCommerce:

WPML comes with the core plugin and add-ons. This architecture allows different people to install different parts that they need. For multilingual WooCommerce sites, you will need the following WPML components:

  • WPML (Core)

  • WPML String Translation

  • WPML Translation Management

  • WPML Media Translation

GoGlobal Partnership

WPML is used on over 400,000 websites and any theme or plugin using the WordPress API can gain multilingual compatibility using WPML.  Why take the risk of not having a multilingual compatible and WooCommerce compatible theme or plugin?

WPML has a GoGlobal Program where we offer free WPML accounts to theme and plugin authors for compatibility testing.  We have numerous themes that are currently compatible including several WooThemes, all of Elegant Themes, Avada, and many themes on ThemeForest.

At WPML we take compatibility seriously with five expert developers and consultants that work full time on compatibility for all theme and plugin authors to gain multilingual compatibility. Sign up for free today to our WPML GoGlobal Program.

Distributing Multilingual-Ready Themes

When you distribute your theme, you want people to be able to use it for single-language and multilingual sites. The design tips that we gave throughout this article mostly rely on WordPress best practices, so your theme code barely includes any specific code for WPML.

Your clients will need to install WPML and its required components to run multilingual sites. As WPML is trademarked (and for other good reasons), you should not bundle WPML with your theme.

Instead, WPML offers a small purchase and auto-install component, which you are very welcome to use. This component lets your users buy WPML directly from inside the WordPress admin. It also credits you with affiliate commission for any such referral.

Integrating this tiny auto-install component in your theme is a great way to show people that your theme is truly compatible with WPML and can power multilingual sites. It also gives your users a streamlined process for buying and installing WPML, without having to use FTP to upload it to their servers.

Summary

Now that we have covered the top seven best practices of making your theme or plugin WooCommerce and Multilingual ready, we hope that you are ready to get started. Being multilingual-ready is easy and possible for every theme author.  

It is as easy as using WordPress best practices such as using `gettext` Functions and properly handling hardcoded WooCommerce Links, to finally adding a Language Configuration File to your theme.  Increase the versatility of your product on the market by focusing on the internationalization of your theme or plugin.

We’re giving away $8,000 in our latest WPML and WooCommerce WordPress Themes Most Wanted event. You’ve got to be in it to win it!

from Tuts+ Code – WordPress http://ift.tt/ZDTyCY

A WordPress Development Process Using Sass and Compass

In this article, we’re going to take a look at how to use Sass and Compass in our WordPress theme development process. We will structure our theme stylesheets in SMACSS fashion and will leverage the power of Compass to generate image sprites for both retina and non-retina devices.

Note that this article is not an introduction to Sass; however, if you are a beginner, still feel free to follow along.

Requirements

Before we jump in, make sure that you have Sass and Compass installed on your machine. If you haven’t installed them yet, follow the instructions on:

There are few GUI based Sass and Compass applications, but I will be using the Terminal (if you’re on Windows, then you can use the Command Prompt). Feel free to use the tool with which you are most comfortable.

Project Setup

Let’s start by creating a folder for our project. Create a new folder on your Desktop and call it tutsplus. Inside it create two new folders: sass and images. The sass folder will contain our Sass files that will form our theme stylesheet, the style.css.

Open the images folder and create two new directories for our theme icons. Call the directories icons and icons@2x. Later, we will use the images in these folders to create a image sprites for our theme. At this point your folders structure should look the following:

Figure 1 The Folders structure
The Folders structure

Compass Configuration

We will use Compass to watch for file changes inside the sass folder and, when a change occurs, it will use the Sass to compile our stylesheets. Every time we launch Compass, it will look for a configuration file in the current directory. That file is called config.rb.

To create the configuration file open your terminal/command prompt and navigate to your tutsplus folder on your desktop:

cd /Desktop/tutsplus/

Next call the compass config config.rb command. This command fill generate the configuration file for you. Open the file in your favorite text editor and make the following changes:

  1. Chage the css_dir = "stylesheets" to: css_dir = "/". This will tell the Compass to output the generated CSS files inside our theme root folder, as this is where the WordPress will look for our theme’s style.css.
  2. Set your prefered output style for the generated CSS. Here, I will set it to expanded style by typing on line 12 output_style = :expanded.
  3. Uncomment lines 14 and 17 by deleting the preceding hash symbol so that the following lines look like relative_assets = true and line_comments = false.

Save your changes. Now your config.rb file should look like the one below:

# Require any additional compass plugins here.

# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "/"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "javascripts"

# You can select your preferred output style here (can be overridden via the command line):
# output_style = :expanded or :nested or :compact or :compressed
output_style = :expanded

# To enable relative paths to assets via compass helper functions. Uncomment:
relative_assets = true

# To disable debugging comments that display the original location of your selectors. Uncomment:
line_comments = false

# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass

Watch For Changes

All right! Now that we have the configuration file, it is the time to create our first Sass file. Create new file inside the sass folder and call it style.scss. Next, launch your Terminal and navigate to the /Desktop/tutsplus/ directory.

Execute the compass watch command. This command will start a process that will continuously look for Sass files changes inside our sass folder. It will find our style.scss file and output its CSS representation as style.css inside our tutsplus directory.

Note that all files inside our sass folder that names does not start with underscore will be processed and outputed in the tutsplus folder. This is exactly what we want for the style.scss file.

An important thing to remember: Don’t make direct changes inside the generated CSS files, as your changes will be lost once you compile again your Sass files.

Decompose

We are going to separate our style.scss into small components using the style guides defined in SMACSS (Scalable and Modular Architecture for CSS). The author of SMACSS is Jonathan Snook and he has published a book about this very topic that I encourage you to read. If you are a Tuts+ member, you can download a copy of it from here.

SMACSS categorizes your CSS rules into five groups:

  1. Base
  2. Layout
  3. Module
  4. State
  5. Theme

Let’s create a folder for each of those categories inside our sass folder. Use the following names: base, layouts, modules, states and themes.

Figure 2 Our SMACSS folder structure
Our SMACSS folder structure

Base

In your base folder, put all of your stylesheets that conform to the SMACSS Base Style Rules. Those stylesheets should apply styles only on element selectors. This is also a good place to put your browser reset CSS.

Compass comes with browser reset based on Eric Meyer’s reset stylesheet. For this project, I’m going to use normalize.css. Download the normalize.css file and place it inside the base directory, then rename it to _normalize.scss. Make sure to change its file extension from css to scss.

Next, we need to import the normalize stylesheet in our style.scss. To do this open the style.scss and add:

// Base 
@import "base/normalize";

As you can see we are omitting the underscore in the file name and its file extension. The Sass preprocessor is smart enought to import the file we wanted.

Layouts

Here, place your theme layout styles. For example, this will include your header, sidebar, footer and page layouts as _header.scss, _sidebar.scss, _footer.scss and _page.scss.

You can use the l- prefix for your layout class names:

// _header.scss
.l-main-header {
    margin: 30px;
    padding: 20px;
    font-size: 16px;
}

// _navigation.scss
.l-main-nav {
    position: relative;
}

This is also a good place for your grid stylesheet. You can read more about SMACSS layout rules, as well.

Modules

Modules are reusable content elements. For example, a blog post is a module in that its rules are re-used on multiple instances of same module. Widgets, shortcodes, and icons are also a type of module. 

A module can contain sub modules. Here is an example of widget module and its title submodule:

<li class="widget">
    <h4 class="widget__title">Recent Posts</h4>
</li>
.widget {
    padding: 10px;
}

.widget__title {
    font-size: 15px;
}

Here we are using the BEM (Block Element Modifier) class naming convention.

States

Place here your stylesheets that control the appearance of your elements depending on some state. If you are building a responsive theme place here your media queries stylesheet.

Let’s create one right now.

Create a new file in your text editor and save it as _media_queries.scss in the /sass/states/ folder. Paste these common screen size rules inside of the file:

/*! =Media Queries
-------------------------------------------------------------- */

/* 956-768px */
@media only screen and (min-width: 768px) and (max-width: 959px) {

}

/* 767-480px */
@media only screen and (min-width: 480px) and (max-width: 767px) {

}

/* 479px */
@media only screen and (max-width: 479px) {

}

Don’t forget to import our newly created stylesheet in our style.scss file:

// Base 
@import "base/normalize";

// States 
@import "states/media_queries"

If you have for example an off-screen navigation menu, here you can put the styles that will controll the appearance when your navigation .is-open or .is-closed, but in most cases you will put those in the layout or module file for the off-canvas navigation.

Themes

This is a good place to put your custom WordPress plugin’s styles. For example, here you can put your custom styles for, say, the Contact Form 7 plugin.

Theme Info

Each WordPress theme’s style.css file should contain meta information about the theme like theme name, author, version and more. We can take advantage of the Sass variables to change that information for each theme we create.

First create a new file called _vars.scss and save it inside the sass folder. In this file we will put all of our variables. If you find that this file grows too big, separate its content to smaller files.

Open the newly created file and enter the following variables:

// Theme Information
//--------------------------------------------//
$theme_name: "My Theme";
$theme_uri: "#";
$theme_description: "My WordPress Theme";
$theme_version: "1.0";
$theme_author: "my name";
$theme_author_uri: "#";
$theme_license: "GPL";
$theme_tags: "responsive-layout, post-formats";

Now we need to create a file that will use the above variables. Using your text editor of choice, create a new file called _theme_info.scss and save it in the sass folder. Fill the _theme_info.scss with the following content:

/*!

Theme Name: #{ $theme_name }
Theme URI: #{ $theme_uri }
Description: #{ $theme_description }
Version: #{ $theme_version }
Author: #{ $theme_author }
Author URI: #{ $theme_author_uri }
License: #{ $theme_license }
License URI: License.txt
Tags: #{ $theme_tags }

*/

The final step is to import our newly created files inside the style.scss, let’s also import the Compass components:

@import "compass";

@import "vars";
@import "theme_info";

// Base 
@import "base/normalize";

// States 
@import "states/media_queries";

Now if you open the processed style.css file it will contain the WordPress theme information comment block with the variables values that you set in _vars.scss file.

Helpers

It is a good practice to use more small more generic CSS classes to style an element rather than using one too specific selector. Follow the DRY – Don’t Repeat Yourself principle. We can create a stylesheet for our small helper classes. To give you an example, I will define some layout and typography helpers. 

Create a new file called _helpers.scss and save it inside the sass folder. Again, as with the variables file, if your helper file get too big to maintain, consider splitting it into smaller files. 

Open the newly created file and paste in:

/*! =Helpers
-------------------------------------------------------------- */

// Layout
//--------------------------------------------//
.left {
    float: left;
}

.right {
    float: right;
}

.clear {
    clear: both;
}

.hide {
    display: none;
}

.hidden {
    opacity: 0;
    visibility: hidden;
}

.clearfix {

    &:before,
    &:after {
        content: " ";
        display: table;
    }

    &:after {
        clear: both;
    }
}

.center-block {
    display: block;
    margin: 0 auto;
}

// Typography
//--------------------------------------------//
.f-normal {
    font-weight: normal;
}

.f-bold {
    font-weight: bold;
}

.f-italic {
    font-style: italic;
}

.t-strike {
    text-decoration: line-through;
}

.t-overline {
    text-decoration: overline;
}

.t-underline {
    text-decoration: underline;
}

.t-left {
    text-align: left;
}

.t-right {
    text-align: right;
}

.t-center {
    text-align: center;
}

As you can see here we are using f- prefix for font-related classes and t- for text-related classes. Save your file and import it inside the style.scss:

@import "compass";

@import "vars";
@import "theme_info";

// Base 
@import "base/normalize";

// Helpers 
@import "helpers";

// States 
@import "states/media_queries";

Generating Sprites

Compass comes with handy methods for generating image sprites. We will place our icons inside our icons and icons@2x folders, where the latter will contain the same icons but in twice the size for devices with retina display.

For this example, I will put inside two icon files: checkmark.png and star.png that you can find in the download package associated with this post.

Figure 3 The icons
The icons

For each icon we will generate a separate CSS class using a Sass list with all of the icon file names. Open the _vars.scss file and add the following code:

// Icons
//--------------------------------------------//
// map *.png icon files
$icons_sprite: sprite-map( "icons/*.png" ); 
$icons_sprite2x: sprite-map( "icons@2x/*.png" );

// generate the icons sprites
$sprites_file: sprite-url( $icons_sprite );
$sprites2x_file: sprties-url( $icons_sprite2x );

$sprites_url: url( "images/" + sprite-path( $icons_sprite ) );
$sprites2x_url: url( "images/" + sprite-path( $icons_sprite2x ) );

// list with theme icons file names (found in icons and icons@2x folders)
$theme_icons: ( "checkmark", "star" );

Compass will find all the *.png image files inside our icons folders and will generate two image sprites in the images folder. Now we want to generate CSS classes for those images.

To find the icon position inside the sprite image, we will create two helper mixins. To do that, create a new file and call it _mixins.scss then open it and paste in the following code:

// Icons
//--------------------------------------------//
@mixin sprite_icon( $name, $sprite ) {
    
    @include sprite-dimensions( $sprite, $name );
    background-position: sprite-position( $sprite, $name );
}

@mixin retina_sprite_icon( $name, $sprite ) {
    
    $pos: sprite-position( $sprite, $name );
    background-position: nth( $pos, 1 ) nth( $pos, 2 ) / 2;
    @include background-size( ceil( image-width( sprite-path( $sprite ) ) / 2 ) auto );
}

Both mixins are accepting an icon name plus a sprite map as arguments. Those mixins will set the width, height and the background position for the icon inside the generated image sprite. The retina_sprite_icon will also set the appropriate background size for the retina icons.

Now it’s time to generate our icons classes. Create a new file called _icons.scss and save it inside the /sass/modules/ folder. Next, paste inside the following content:

/*! =Icons 
-------------------------------------------------------------- */
@if ( length( $theme_icons ) > 0 ) {

    .icon {
        display: inline-block;
        background: $sprites_url no-repeat;
    }
                
    @each $icon in $theme_icons {
        
        .#{ "icon--" + $icon } {
            
            @include sprite_icon( $icon, $icons_sprite );
        }
    }

    @media
    only screen and (-webkit-min-device-pixel-ratio: 2),
    only screen and (   min--moz-device-pixel-ratio: 2),
    only screen and (     -o-min-device-pixel-ratio: 2/1),
    only screen and (        min-device-pixel-ratio: 2),
    only screen and (                min-resolution: 192dpi),
    only screen and (                min-resolution: 2dppx) {

        .icon {
            background: $sprites2x_url;
        }

        @each $icon in $theme_icons {
            
            .#{ "icon--" + $icon } {

                @include retina_sprite_icon( $icon, $icons_sprite2x );
            }
        }
    }

}

Here, we are looping through our icon names list which is identified by  $theme_icons and generating both retina and non retina style rules using our icon mixins. From there, we generate a class called .icon that will be the base module for our icons and then the module modifiers classes for each icon in the list. 

In this example, it will generate the .icon--checkmark and .icon--star classes. Here is an example usage of the star icon:

<i class="icon icon--star"></i>

Finally let’s import our mixins and icons module inside the style.scss file:

@import "compass";

@import "vars";
@import "mixins";
@import "theme_info";

// Base 
@import "base/normalize";

// Helpers 
@import "helpers";

// Modules
@import "modules/icons";

// States
@import "states/media_queries";

Conclusion

Sass and Compass are both powerful utilities and can go a long way in improving your WordPress theme development and WordPress plugin development. This guide aims to set you on the road to creating a more refined process for working with WordPress.

For those who are curious and want to read more about some of the information covered in this tutorial, please review the following articles:

from Tuts+ Code – WordPress http://ift.tt/1uxFKmQ

A Practical Use of WordPress Global Variables

In the first article in this series, we reviewed an introduction to WordPress global variables. Specifically, we said that they are variables that hold a variety information that can be accessed from anywhere in the WordPress page lifecycle.

We learned how to access a global variable and display various details about the latest post using the $post global variable. In today’s article, we will dive further into global variables by learning how to access them to display the author information.

Retrieving Author Data

Most information about the author of the given post or pages are available through the global variable $authordata.  To get started with the $authordata global cariable we need to use the following snippet:

<?php

    global $authordata;   
    print_r( $authordata ); 

Next, let’s edit the page.php of the twentyfourteen theme and insert the above snippet right after the get_template_part(‘content’, ‘page’) which fetches the content and displays it on the page.  

We should have the following code in the page template now:

<div id="primary" class="content-area">
    <div id="content" class="site-content" role="main">

		<?php
		while ( have_posts() ) : the_post();
	
			get_template_part( 'content', 'page' );
	
			global $authordata; 
			print_r( $authordata );
	
			// If comments are open or we have at least one comment, load up the comment template.
	
			if ( comments_open() || get_comments_number() ) {
				comments_template();
			}
	
		endwhile;
		?>

	</div><!-- #content -->

</div><!-- #primary -->

When we save the page.php and access an existing WordPress page we should be able to see the following result:

Authordatapng

We could thus access each of the individual values of the above object as follows:

<?php
    global $authordata;
    echo $authordata->display_name;

The above snippet would print the display name of the author who wrote the page. Similarly you could try writing a code snippet that would display the other values of the $authordata such as the author username, author email, etc. 

Remember that we could use the $authordata in powerful ways in our theme and plugin development to perform various functions.

Let us perform a hands on activity with the $authordata global variable to get the list of the three latest posts of the author and display the posts as links. This will require the following steps:

First, add the function to fetch and display three posts by the author in functions.php

<?php
function tutsplus_display_three_posts() {

    global $authordata, $post;  //Declare Global Variables

	$authors_three_posts = get_posts( 
    						array(
								'author'         => $authordata->ID, 
								'posts_per_page' => 3
							)
						   );                          

	echo '<h5>Latest Posts</h5>';
	
	$output = '<ul>';
	foreach ( $authors_three_posts as $authors_post ) {
		$output .= '<li><a href="' . get_permalink( $authors_post->ID ) . '">' . get_the_title($authors_post->ID) . '</a></li>';
	
	}
	$output .= '</ul>';
	
	return $output;

}
  • First, we declare that we are accessing the global variables $authordata and $post. We proceed to use get_posts WordPress template tag to fetch three posts by the current author and store it in an array called $author_three_posts.
  • Secondly, we loop through the $author_three_posts array using a foreach loop to print the title of the post that links to the actual post, here we use the get_permalink and get_the_title to fetch the link and the title from the post ID.
  • Finally, we return the printed value as a variable called $output.

Next, call the tutsplus_display_three_posts() function name to be executed in the single.php of the twentyfourteen theme:

<div id="primary" class="content-area">
    <div id="content" class="site-content" role="main">

	<?php
	while ( have_posts() ) : the_post();
	
		get_template_part( 'content', get_post_format() );
	
		echo tutsplus_display_three_posts();
	
		twentyfourteen_post_nav();
	
		if ( comments_open() || get_comments_number() ) {
			comments_template();
		}
	
	endwhile;
	?>

	</div><!-- #content -->
</div><!-- #primary -->
After that, open a single post page to test the execution of our code:

LatestPostspng

Wrapping It Up

With that we conclude the second part of the series. As you can see from the above example, it is possible to use the global variables to perform simple operations to complex functions within WordPress development.

References

from Tuts+ Code – WordPress http://ift.tt/1uxFKmF