Web design

A Simple And Easy Guide To Understand Sass

A while ago Thoriq Firdaus wrote a great article about getting started with Sass which showed you how to install and use this highly useful CSS preprocessor language (you might want to check it out, you know, to get started).

In this article I thought I’d give you a bit more insight into what you can do with Sass and how developers use it every day to create better and more modular CSS code. Skip ahead to the section you want:

Tools Of The Trade

Thoriq showed you how you can use Sass from the command line using the sass --watch command.

If you prefer GUI tools, you can go with my personal favourite app, Codekit, a web developer tool for compiling Sass, concatenating, autoprefixing and much more. Prepros is another very capable application which can be used on all systems. Both are paid applications but are well worth it if you’ll be using them in the long run.

If you just want to try out Sass without paying for anything you can use the terminal, or Koala (here’s our review), a free cross-platform feature-rich app, which can hold its ground against premium counterparts.

Variables

One of the first things you’ll need to wrap your head around is variables. If you come from a PHP or other similar coding language background this will be second nature to you. Variables are for storing bits and pieces of reusable information, like a color value for example:

$primary_color: #666666;

.button 
    color: $primary_color;


.important 
    color: $primary_color;

This may not seem that useful here, but imagine having 3,000 lines of code. If your color scheme changes you would need to replace each color value in CSS. With Sass you can just modify the value of the $primary_color variable and be done with it.

Variables are used for storing font names, sizes, colors and a host of other information. For larger projects it may we worth extracting all your variables into a separate file (we’ll take a look at how this is done soon). What this allows you to do is recolor your whole project and change fonts and other key aspects without ever touching actual CSS rules. All you need to do is modify some variables.

Nesting

Another basic feature Sass gives you is the ability to nest rules. Let’s assume that you’re building a navigation menu. You have a nav element which contains an unordered list, list items and links. In CSS you may do something like this:

#header nav 
    /* Rules for the nav area */


#header nav ul 
    /* Rules for the menu */


#header nav li 
    /* Rules for list items */


#header nav a 
    /* Rules for links */

In the selectors, we are repeating ourselves a lot. If elements have common roots, we can use nesting to write our rules in a much cleaner way.

Here’s how the above code could look in Sass:

#header 
    nav 
        /* Rules for the nav area */
    

    ul 
        /* Rules for the menu */
    

    li 
        /* Rules for list items */
    

    a 
        /* Rules for links */
    

Nesting is extremely useful because it makes stylesheets (a lot) more readable. By using nesting together with proper indentation you can achieve highly legible code structures, even if you have a fair amount of code.

One drawback of nesting is that it can lead to unnecessary specificity. In the example above I’ve refered to links with #header nav a. You could also use #header nav ul li a which would probably be too much.

In Sass, it is much easier to be very specific since all you need to do is nest your rules. The following is far less readable and quite specific.

#header 
    nav 
        /* Rules for the nav area */
        ul 
            /* Rules for the menu */
            li 
                /* Rules for list items */
                a 
                    /* Rules for links */
                
            
        
    

Extending Rulesets

Extending will be familiar if you’ve working with object oriented languages. It is best understood through an example, let’s create 3 buttons which are slight variations of each other.

.button 
    display: inline-block;
    color: #000;
    background: #333;
    border-radius:4px;
    padding:8px 11px;


.button-primary 
    @extend .button;
    background: #0091C2


.button-small 
    @extend .button;
    font-size:0.9em;
    padding:3px 8px;

The .button-primary and .button-small classes all extend the .button class which means that they take on all its properties and then define their own.

This is immensely useful in many situations where variations of an element can be used. Messages (alert / success / error), buttons (colors, sizes), menu types and so on could all use the extending functionality for great CSS efficiency.

One caveat of extends is that they won’t work in media queries as you would expect. This is a bit more advanced but you can read all about this behavior in Understanding Placeholder Selectors – placeholder selectors are special kind of extend which we’ll talk about soon.

Mixins

Mixins are another favorite feature of preprocessor users. Mixins are reusable rulesets – perfect for vendor-specific rules or for shorthanding long CSS rules.

How about creating a transition rule for hover elements:

@mixing hover-effect 
    -webkit-transition: background-color 200ms;
    -moz-transition: background-color 200ms;
    -o-transition: background-color 200ms;
    transition: background-color 200ms;


a 
    @include hover-effect;


.button 
    @include hover-effect;

Mixins also allow you to use variables to define the values within the mixin. We could rewrite the example above to give us control over the exact time of the transition. We may want buttons to transition a tiny bit slower for example.

@mixin hover-effect( $speed ) 
    -webkit-transition: background-color $speed;
    -moz-transition: background-color $speed;
    -o-transition: background-color $speed;
    transition: background-color $speed;


a 
    @include hover-effect(200ms);


.button 
    @include hover-effect(300ms);

Placeholder Selectors

Placeholder selectors were introduced with Sass 3.2 and solved a problem which could cause a bit of bloat in your generated CSS code. Take a look at this code which creates error messages:

.message 
    font-size:1.1em;
    padding:11px;
    border-width:1px;
    border-style:solid;


.message-danger 
    @extend .button;
    background: #C20030;
    color:#fff;
    border-color: #A8002A;


.message-success 
    @extend .button;
    background: #7EA800;
    color:#fff;
    border-color: #6B8F00;

It is most likely that the message class will never be used in our HTML: it has been created to be extended, not used as is. This causes a little bit of bloat in your generated CSS. To make your code more efficient you can use the placeholder selector which is indicated with a percentage sign:

%message 
    font-size:1.1em;
    padding:11px;
    border-width:1px;
    border-style:solid;


.message-danger 
    @extend %button;
    background: #C20030;
    color:#fff;
    border-color: #A8002A;


.message-success 
    @extend %button;
    background: #7EA800;
    color:#fff;
    border-color: #6D9700;

At this stage you may be wondering what the difference between extends and mixins are. If you use placeholders they behave like a parameter-less mixin. This is true, but the output in CSS differs. The difference is that mixins duplicate rules while placeholders will make sure that the same rules share selectors, resulting in less CSS in the end.

Operations

It’s hard to resist the pun here, but I’ll refrain from any medical jokes for now. Operators allow you to do some math in your CSS code and can be pretty darn helpful. The example in the Sass guide is perfect for showcasing this:

.container  width: 100%; 

article 
  float: left;
  width: 600px / 960px * 100%;


aside 
  float: right;
  width: 300px / 960px * 100%;

The example above creates a 960px based grid system with minimum hassle. It will compile down nicely to the following CSS:

.container 
  width: 100%;


article 
  float: left;
  width: 62.5%;


aside 
  float: right;
  width: 31.25%;

One great use I find for operations is to actually mix colors. If you take a look at the success message Sass above it’s not clear that the color of the background and the border have some sort of relationship. By subtracting a shade of gray we can darken the color, making the relationship visible:

$primary: #7EA800;

.message-success 
    @extend %button;
    background: $primary;
    color:#fff;
    border-color: $primary - #111;

The lighter the subtracted color, the darker the resulting shade will be. The lighter the added color, the lighter the resulting shade.

Functions

There are a great number of functions to use: Number functions, string functions, list functions, color functions and more. Take a look at the long list in the developer documentation. I’ll take a look at a couple here just to show you how they work.

The lighten and darken function can be used to change the lightness of a color. This is better than subtracting shades, it makes everything even more modular and obvious. Take a look at our previous example using the darkening function.

$primary: #7EA800;

.message-success 
    @extend %button;
    background: $primary;
    color:#fff;
    border-color: darken( $primary, 5 );

The second argument of the function is the percentage of darkening required. All functions have parameters; take a look at the documentation to see what they are! Here are a few other self-explanatory color functions: desaturate, saturate, invert, grayscale.

The ceil function, just like in PHP, returns a number rounded to the next whole number. This can be used when calculating column widths or if you don’t want to use a lot of decimal places in the final CSS.

.title 
    font-size: ceil( $heading_size * 1.3314 );

Overview

The features in Sass give us great power to write better CSS with less effort. The proper use of mixins, extends, functions and variables will make our stylesheets more maintainable, more legible and easier to write.

If you’re interested in another similar CSS preprocessor I suggest taking a look at LESS (or check out our beginner’s guide) – the underlying principal is much the same!

Standard
Web design

A Simple And Easy Guide To Understand Sass

A while ago Thoriq Firdaus wrote a great article about getting started with Sass which showed you how to install and use this highly useful CSS preprocessor language (you might want to check it out, you know, to get started).

In this article I thought I’d give you a bit more insight into what you can do with Sass and how developers use it every day to create better and more modular CSS code. Skip ahead to the section you want:

Tools Of The Trade

Thoriq showed you how you can use Sass from the command line using the sass --watch command.

If you prefer GUI tools, you can go with my personal favourite app, Codekit, a web developer tool for compiling Sass, concatenating, autoprefixing and much more. Prepros is another very capable application which can be used on all systems. Both are paid applications but are well worth it if you’ll be using them in the long run.

If you just want to try out Sass without paying for anything you can use the terminal, or Koala (here’s our review), a free cross-platform feature-rich app, which can hold its ground against premium counterparts.

Variables

One of the first things you’ll need to wrap your head around is variables. If you come from a PHP or other similar coding language background this will be second nature to you. Variables are for storing bits and pieces of reusable information, like a color value for example:

 $primary_color: #666666; .button  color: $primary_color;  .important  color: $primary_color;  

This may not seem that useful here, but imagine having 3,000 lines of code. If your color scheme changes you would need to replace each color value in CSS. With Sass you can just modify the value of the $primary_color variable and be done with it.

Variables are used for storing font names, sizes, colors and a host of other information. For larger projects it may we worth extracting all your variables into a separate file (we’ll take a look at how this is done soon). What this allows you to do is recolor your whole project and change fonts and other key aspects without ever touching actual CSS rules. All you need to do is modify some variables.

Nesting

Another basic feature Sass gives you is the ability to nest rules. Let’s assume that you’re building a navigation menu. You have a nav element which contains an unordered list, list items and links. In CSS you may do something like this:

 #header nav  /* Rules for the nav area */  #header nav ul  /* Rules for the menu */  #header nav li  /* Rules for list items */  #header nav a  /* Rules for links */  

In the selectors, we are repeating ourselves a lot. If elements have common roots, we can use nesting to write our rules in a much cleaner way.

Here’s how the above code could look in Sass:

 #header  nav  /* Rules for the nav area */  ul  /* Rules for the menu */  li  /* Rules for list items */  a  /* Rules for links */   

Nesting is extremely useful because it makes stylesheets (a lot) more readable. By using nesting together with proper indentation you can achieve highly legible code structures, even if you have a fair amount of code.

One drawback of nesting is that it can lead to unnecessary specificity. In the example above I’ve refered to links with #header nav a. You could also use #header nav ul li a which would probably be too much.

In Sass, it is much easier to be very specific since all you need to do is nest your rules. The following is far less readable and quite specific.

 #header  nav  /* Rules for the nav area */ ul  /* Rules for the menu */ li  /* Rules for list items */ a  /* Rules for links */      

Extending Rulesets

Extending will be familiar if you’ve working with object oriented languages. It is best understood through an example, let’s create 3 buttons which are slight variations of each other.

 .button  display: inline-block; color: #000; background: #333; border-radius:4px; padding:8px 11px;  .button-primary  @extend .button; background: #0091C2  .button-small  @extend .button; font-size:0.9em; padding:3px 8px;  

The .button-primary and .button-small classes all extend the .button class which means that they take on all its properties and then define their own.

This is immensely useful in many situations where variations of an element can be used. Messages (alert / success / error), buttons (colors, sizes), menu types and so on could all use the extending functionality for great CSS efficiency.

One caveat of extends is that they won’t work in media queries as you would expect. This is a bit more advanced but you can read all about this behavior in Understanding Placeholder Selectors – placeholder selectors are special kind of extend which we’ll talk about soon.

Mixins

Mixins are another favorite feature of preprocessor users. Mixins are reusable rulesets – perfect for vendor-specific rules or for shorthanding long CSS rules.

How about creating a transition rule for hover elements:

 @mixing hover-effect  -webkit-transition: background-color 200ms; -moz-transition: background-color 200ms; -o-transition: background-color 200ms; transition: background-color 200ms;  a  @include hover-effect;  .button  @include hover-effect;  

Mixins also allow you to use variables to define the values within the mixin. We could rewrite the example above to give us control over the exact time of the transition. We may want buttons to transition a tiny bit slower for example.

 @mixin hover-effect( $speed )  -webkit-transition: background-color $speed; -moz-transition: background-color $speed; -o-transition: background-color $speed; transition: background-color $speed;  a  @include hover-effect(200ms);  .button  @include hover-effect(300ms);  

Placeholder Selectors

Placeholder selectors were introduced with Sass 3.2 and solved a problem which could cause a bit of bloat in your generated CSS code. Take a look at this code which creates error messages:

 .message  font-size:1.1em; padding:11px; border-width:1px; border-style:solid;  .message-danger  @extend .button; background: #C20030; color:#fff; border-color: #A8002A;  .message-success  @extend .button; background: #7EA800; color:#fff; border-color: #6B8F00;  

It is most likely that the message class will never be used in our HTML: it has been created to be extended, not used as is. This causes a little bit of bloat in your generated CSS. To make your code more efficient you can use the placeholder selector which is indicated with a percentage sign:

 %message  font-size:1.1em; padding:11px; border-width:1px; border-style:solid;  .message-danger  @extend %button; background: #C20030; color:#fff; border-color: #A8002A;  .message-success  @extend %button; background: #7EA800; color:#fff; border-color: #6D9700;  

At this stage you may be wondering what the difference between extends and mixins are. If you use placeholders they behave like a parameter-less mixin. This is true, but the output in CSS differs. The difference is that mixins duplicate rules while placeholders will make sure that the same rules share selectors, resulting in less CSS in the end.

Operations

It’s hard to resist the pun here, but I’ll refrain from any medical jokes for now. Operators allow you to do some math in your CSS code and can be pretty darn helpful. The example in the Sass guide is perfect for showcasing this:

 .container  width: 100%;  article  float: left; width: 600px / 960px * 100%;  aside  float: right; width: 300px / 960px * 100%;  

The example above creates a 960px based grid system with minimum hassle. It will compile down nicely to the following CSS:

 .container  width: 100%;  article  float: left; width: 62.5%;  aside  float: right; width: 31.25%;  

One great use I find for operations is to actually mix colors. If you take a look at the success message Sass above it’s not clear that the color of the background and the border have some sort of relationship. By subtracting a shade of gray we can darken the color, making the relationship visible:

 $primary: #7EA800; .message-success  @extend %button; background: $primary; color:#fff; border-color: $primary - #111;  

The lighter the subtracted color, the darker the resulting shade will be. The lighter the added color, the lighter the resulting shade.

Functions

There are a great number of functions to use: Number functions, string functions, list functions, color functions and more. Take a look at the long list in the developer documentation. I’ll take a look at a couple here just to show you how they work.

The lighten and darken function can be used to change the lightness of a color. This is better than subtracting shades, it makes everything even more modular and obvious. Take a look at our previous example using the darkening function.

 $primary: #7EA800; .message-success  @extend %button; background: $primary; color:#fff; border-color: darken( $primary, 5 );  

The second argument of the function is the percentage of darkening required. All functions have parameters; take a look at the documentation to see what they are! Here are a few other self-explanatory color functions: desaturate, saturate, invert, grayscale.

The ceil function, just like in PHP, returns a number rounded to the next whole number. This can be used when calculating column widths or if you don’t want to use a lot of decimal places in the final CSS.

 .title  font-size: ceil( $heading_size * 1.3314 );  

Overview

The features in Sass give us great power to write better CSS with less effort. The proper use of mixins, extends, functions and variables will make our stylesheets more maintainable, more legible and easier to write.

If you’re interested in another similar CSS preprocessor I suggest taking a look at LESS (or check out our beginner’s guide) – the underlying principal is much the same!



Standard
Web design

Using The TinyMCE Editor In WordPress [Guide]

Although they may not know its name, everyone who uses WordPress is familiar with the TinyMCE editor. It’s the editor you use when you create or edit your content – the one with the buttons for creating bold text, headings, text alignment and so on is. That’s what we’ll be taking a look at in this post, and I’m going to show you how you can add functionality and how you can use it in your plugins.

The editor is built on a platform-independent Javascript system called TinyMCE which is used in a number of projects on the Web. It has a great API which WordPress allows you to tap into to create your own buttons and to add it to other locations within WordPress.

Adding Available Buttons

WordPress uses some options available in TinyMCE to disable particular buttons – such as superscript, subscript and horizontal rules – in order to clean up the interface. They can be added back without too much fuss.

The first step is to create a plugin. Take a look at the WordPress codex on how to do that. In a nutshell, you can get by with creating a folder named ‘my-mce-plugin’ in the wp-content/plugins folder. Create a file with the same name, with a PHP extension: my-mce-plugin.php.

Inside that file paste the following:

<?php
/**
    *Plugin Name: My TinyMCE plugin
    *Description: A plugin for adding custom functionality to the WordPress TinyMCE plugin.
*/

Once done you should be able to select this plugin in WordPress and activate it. All the code from now on can be pasted inside this file.

So, back to enabling some built-in but hidden buttons. Here’s the code that allows us to enable the 3 buttons I mentioned:

add_filter( 'mce_buttons_2', 'my_tinymce_buttons' );
function my_tinymce_buttons( $buttons ) 
    $buttons[] = 'superscript';
    $buttons[] = 'subscript';
    $buttons[] = hr;
    return $buttons;

To know which buttons can be added and what they are called, take a look at the list found in the TinyMCE documentation for controls.

Creating Our Own Buttons

How about creating our own buttons from scratch? Many websites use Prism for code highlighting which uses a very semantic approach to marking up code segments. You have to wrap your code within <code> and <pre> tags, something like this:

<pre><code>$variable = 'value'</code></pre>

Let’s create a button which will do this for us!

This is a three-step process. You will need to add a button, load a javascript file and actually write the content of the Javascript file. Let’s get started!

Adding the button and loading the Javascript file is pretty straightforward, here’s the code I used to get it done:

add_filter( 'mce_buttons', 'pre_code_add_button' );
function pre_code_add_button( $buttons ) 
    $buttons[] = 'pre_code_button';
    return $buttons;

add_filter( 'mce_external_plugins', 'pre_code_add_javascript' );
function pre_code_add_javascript( $plugin_array ) 
	$plugin_array['pre_code_button'] = get_template_directory_uri() . '/tinymce-plugin.js';
	return $plugin_array;

When I see tutorials about this I frequently see 2 problems.

They neglect to mention that the button name added in the pre_code_add_button() function must be the same as the key for the $plugin_array variable in the pre_code_add_javascript() function. We will also need to use the same string in our Javascript later on.

Some tutorials also use an additional admin_head hook to wrap everything up. While this will work, it is not required and since the Codex does not use it, it should probably be avoided.

The next step is to write some Javascript to implement our functionality. Here’s what I used to get the <pre> and <code> tags output all at once.

(function() 
    tinymce.PluginManager.add('pre_code_button', function( editor, url ) 
        editor.addButton( 'pre_code_button', 
            text: 'Prism',
            icon: false,
            onclick: function() 
            var selected = tinyMCE.activeEditor.selection.getContent();
            var content = '<pre><code>' + selected + '</code></pre>';
            editor.insertContent( content + "n" );
            
        );
    );
)();

Most of this is dictated by how a TinyMCE plugin is supposed to be coded, you can find some information about that in the TinyMCE documentation. For now, all you need to know is that the name of your button (pre_code_button) should be used in line 2 and 3. The value of "text" in line 4 will be displayed if you do not use an icon (we’ll take a look at adding icons in a moment).

The onclick method dictates what this button does when it is clicked. I want to use it to wrap selected text within the HTML structure discussed earlier.

The selected text can be grabbed using tinyMCE.activeEditor.selection.getContent(). Then, I wrap the elements around it and insert it, replacing the highlighted content with the new element. I’ve also added a new line so I can easily start writing after the code element.

If you want to use an icon I suggest selecting one from the Dashicons set which ships with WordPress. The Developer Reference has a great tool for finding icons and their CSS/HTML/Glyph. Find the code symbol and note the unicode underneath it: f475.

We’ll need to attach a stylesheet to our plugin and then add a simple style to display our icon. First up, let’s add our style to WordPress:

add_action( 'admin_enqueue_scripts', 'pre_code_styles' );
function pre_code_styles() 
	wp_enqueue_style( 'pre_code_button', plugins_url( '/style.css', __FILE__ ) );

Go back to the Javascript and next to the icon in the addButton function, replace “false” with a class you would like your button to have – I used pre_code_button.

Now create the style.css file in your plugin directory and add the following CSS:

i.mce-i-pre_code_button:before 
	font-family:dashicons;
	content: "f475";

Note that the button will receive the mce-i-[your class here] class which you can use to target and add styles. Specify the font as dashicons and the content using the unicode value from earlier.

Using TinyMCE Elsewhere

Plugins often create textareas for entering longer text, wouldn’t it be great if we could use TinyMCE there as well? Of course we can, and it’s pretty easy. The wp_editor() function allows us to output one anywhere in admin, here’s how it looks:

wp_editor( $initial_content, $element_id, $settings );

The first parameter sets the initial content for the box. This could be used to load an option from the database, for example. The second parameter sets the HTML element’s ID. The third parameter is an array of settings. To read about the exact settings you can use, take a look at the wp editor documentation.

The most important setting is the textarea_name. This populates the name attribute of the textarea element, allowing you to save the data easily. Here’s how my editor looks when used in an options page:

$settings = array( 'textarea_name' => 'buyer_bio' );
wp_editor( get_option('buyer_bio'), 'buyer_bio', $settings );

This is equivalent to writing the following code, which would result in a simple textarea:

<textarea id='buyer_bio' class='buyer_bio'><?php get_option( 'buyer_bio' ) ?></textarea>

Conclusion

The TinyMCE editor is a user-friendly way of allowing users more flexibility when entering content. It allows those who don’t want to format their content to just type it up and be done with it, and those who want to fiddle around with it to spend as much time as they need getting it just right.

Creating new buttons and functionality can be done in a very modular way, and we’ve only just scratched the surface of the possibilities. If you know of a particularly good TinyMCE plugin or use case which has helped you a lot, do let us know in the comments below!

Standard
Web design

Using The TinyMCE Editor In WordPress [Guide]

Although they may not know its name, everyone who uses WordPress is familiar with the TinyMCE editor. It’s the editor you use when you create or edit your content – the one with the buttons for creating bold text, headings, text alignment and so on is. That’s what we’ll be taking a look at in this post, and I’m going to show you how you can add functionality and how you can use it in your plugins.

The editor is built on a platform-independent Javascript system called TinyMCE which is used in a number of projects on the Web. It has a great API which WordPress allows you to tap into to create your own buttons and to add it to other locations within WordPress.

Adding Available Buttons

WordPress uses some options available in TinyMCE to disable particular buttons – such as superscript, subscript and horizontal rules – in order to clean up the interface. They can be added back without too much fuss.

The first step is to create a plugin. Take a look at the WordPress codex on how to do that. In a nutshell, you can get by with creating a folder named ‘my-mce-plugin’ in the wp-content/plugins folder. Create a file with the same name, with a PHP extension: my-mce-plugin.php.

Inside that file paste the following:

 <?php /** *Plugin Name: My TinyMCE plugin *Description: A plugin for adding custom functionality to the WordPress TinyMCE plugin. */ 

Once done you should be able to select this plugin in WordPress and activate it. All the code from now on can be pasted inside this file.

So, back to enabling some built-in but hidden buttons. Here’s the code that allows us to enable the 3 buttons I mentioned:

 add_filter( 'mce_buttons_2', 'my_tinymce_buttons' ); function my_tinymce_buttons( $buttons )  $buttons[] = 'superscript'; $buttons[] = 'subscript'; $buttons[] = hr; return $buttons;  

To know which buttons can be added and what they are called, take a look at the list found in the TinyMCE documentation for controls.

Creating Our Own Buttons

How about creating our own buttons from scratch? Many websites use Prism for code highlighting which uses a very semantic approach to marking up code segments. You have to wrap your code within <code> and <pre> tags, something like this:

<pre><code>$variable = 'value'</code></pre>

Let’s create a button which will do this for us!

This is a three-step process. You will need to add a button, load a javascript file and actually write the content of the Javascript file. Let’s get started!

Adding the button and loading the Javascript file is pretty straightforward, here’s the code I used to get it done:

 add_filter( 'mce_buttons', 'pre_code_add_button' ); function pre_code_add_button( $buttons )  $buttons[] = 'pre_code_button'; return $buttons;  add_filter( 'mce_external_plugins', 'pre_code_add_javascript' ); function pre_code_add_javascript( $plugin_array )  $plugin_array['pre_code_button'] = get_template_directory_uri() . '/tinymce-plugin.js'; return $plugin_array;  

When I see tutorials about this I frequently see 2 problems.

They neglect to mention that the button name added in the pre_code_add_button() function must be the same as the key for the $plugin_array variable in the pre_code_add_javascript() function. We will also need to use the same string in our Javascript later on.

Some tutorials also use an additional admin_head hook to wrap everything up. While this will work, it is not required and since the Codex does not use it, it should probably be avoided.

The next step is to write some Javascript to implement our functionality. Here’s what I used to get the <pre> and <code> tags output all at once.

 (function()  tinymce.PluginManager.add('pre_code_button', function( editor, url )  editor.addButton( 'pre_code_button',  text: 'Prism', icon: false, onclick: function()  var selected = tinyMCE.activeEditor.selection.getContent(); var content = '<pre><code>' + selected + '</code></pre>'; editor.insertContent( content + "n" );  ); ); )(); 

Most of this is dictated by how a TinyMCE plugin is supposed to be coded, you can find some information about that in the TinyMCE documentation. For now, all you need to know is that the name of your button (pre_code_button) should be used in line 2 and 3. The value of "text" in line 4 will be displayed if you do not use an icon (we’ll take a look at adding icons in a moment).

The onclick method dictates what this button does when it is clicked. I want to use it to wrap selected text within the HTML structure discussed earlier.

The selected text can be grabbed using tinyMCE.activeEditor.selection.getContent(). Then, I wrap the elements around it and insert it, replacing the highlighted content with the new element. I’ve also added a new line so I can easily start writing after the code element.

If you want to use an icon I suggest selecting one from the Dashicons set which ships with WordPress. The Developer Reference has a great tool for finding icons and their CSS/HTML/Glyph. Find the code symbol and note the unicode underneath it: f475.

We’ll need to attach a stylesheet to our plugin and then add a simple style to display our icon. First up, let’s add our style to WordPress:

 add_action( 'admin_enqueue_scripts', 'pre_code_styles' ); function pre_code_styles()  wp_enqueue_style( 'pre_code_button', plugins_url( '/style.css', __FILE__ ) );  

Go back to the Javascript and next to the icon in the addButton function, replace “false” with a class you would like your button to have – I used pre_code_button.

Now create the style.css file in your plugin directory and add the following CSS:

 i.mce-i-pre_code_button:before  font-family:dashicons; content: "f475";  

Note that the button will receive the mce-i-[your class here] class which you can use to target and add styles. Specify the font as dashicons and the content using the unicode value from earlier.

Using TinyMCE Elsewhere

Plugins often create textareas for entering longer text, wouldn’t it be great if we could use TinyMCE there as well? Of course we can, and it’s pretty easy. The wp_editor() function allows us to output one anywhere in admin, here’s how it looks:

wp_editor( $initial_content, $element_id, $settings );

The first parameter sets the initial content for the box. This could be used to load an option from the database, for example. The second parameter sets the HTML element’s ID. The third parameter is an array of settings. To read about the exact settings you can use, take a look at the wp editor documentation.

The most important setting is the textarea_name. This populates the name attribute of the textarea element, allowing you to save the data easily. Here’s how my editor looks when used in an options page:

$settings = array( 'textarea_name' => 'buyer_bio' );
wp_editor( get_option('buyer_bio'), 'buyer_bio', $settings );

This is equivalent to writing the following code, which would result in a simple textarea:

<textarea id='buyer_bio' class='buyer_bio'><?php get_option( 'buyer_bio' ) ?></textarea>

Conclusion

The TinyMCE editor is a user-friendly way of allowing users more flexibility when entering content. It allows those who don’t want to format their content to just type it up and be done with it, and those who want to fiddle around with it to spend as much time as they need getting it just right.

Creating new buttons and functionality can be done in a very modular way, and we’ve only just scratched the surface of the possibilities. If you know of a particularly good TinyMCE plugin or use case which has helped you a lot, do let us know in the comments below!



Standard
Web design

Using The TinyMCE Editor In WordPress [Guide]

Although they may not know its name, everyone who uses WordPress is familiar with the TinyMCE editor. It’s the editor you use when you create or edit your content – the one with the buttons for creating bold text, headings, text alignment and so on is. That’s what we’ll be taking a look at in this post, and I’m going to show you how you can add functionality and how you can use it in your plugins.

The editor is built on a platform-independent Javascript system called TinyMCE which is used in a number of projects on the Web. It has a great API which WordPress allows you to tap into to create your own buttons and to add it to other locations within WordPress.

Adding Available Buttons

WordPress uses some options available in TinyMCE to disable particular buttons – such as superscript, subscript and horizontal rules – in order to clean up the interface. They can be added back without too much fuss.

The first step is to create a plugin. Take a look at the WordPress codex on how to do that. In a nutshell, you can get by with creating a folder named ‘my-mce-plugin’ in the wp-content/plugins folder. Create a file with the same name, with a PHP extension: my-mce-plugin.php.

Inside that file paste the following:

 <?php /** *Plugin Name: My TinyMCE plugin *Description: A plugin for adding custom functionality to the WordPress TinyMCE plugin. */ 

Once done you should be able to select this plugin in WordPress and activate it. All the code from now on can be pasted inside this file.

So, back to enabling some built-in but hidden buttons. Here’s the code that allows us to enable the 3 buttons I mentioned:

 add_filter( 'mce_buttons_2', 'my_tinymce_buttons' ); function my_tinymce_buttons( $buttons )  $buttons[] = 'superscript'; $buttons[] = 'subscript'; $buttons[] = hr; return $buttons;  

To know which buttons can be added and what they are called, take a look at the list found in the TinyMCE documentation for controls.

Creating Our Own Buttons

How about creating our own buttons from scratch? Many websites use Prism for code highlighting which uses a very semantic approach to marking up code segments. You have to wrap your code within <code> and <pre> tags, something like this:

<pre><code>$variable = 'value'</code></pre>

Let’s create a button which will do this for us!

This is a three-step process. You will need to add a button, load a javascript file and actually write the content of the Javascript file. Let’s get started!

Adding the button and loading the Javascript file is pretty straightforward, here’s the code I used to get it done:

 add_filter( 'mce_buttons', 'pre_code_add_button' ); function pre_code_add_button( $buttons )  $buttons[] = 'pre_code_button'; return $buttons;  add_filter( 'mce_external_plugins', 'pre_code_add_javascript' ); function pre_code_add_javascript( $plugin_array )  $plugin_array['pre_code_button'] = get_template_directory_uri() . '/tinymce-plugin.js'; return $plugin_array;  

When I see tutorials about this I frequently see 2 problems.

They neglect to mention that the button name added in the pre_code_add_button() function must be the same as the key for the $plugin_array variable in the pre_code_add_javascript() function. We will also need to use the same string in our Javascript later on.

Some tutorials also use an additional admin_head hook to wrap everything up. While this will work, it is not required and since the Codex does not use it, it should probably be avoided.

The next step is to write some Javascript to implement our functionality. Here’s what I used to get the <pre> and <code> tags output all at once.

 (function()  tinymce.PluginManager.add('pre_code_button', function( editor, url )  editor.addButton( 'pre_code_button',  text: 'Prism', icon: false, onclick: function()  var selected = tinyMCE.activeEditor.selection.getContent(); var content = '<pre><code>' + selected + '</code></pre>'; editor.insertContent( content + "n" );  ); ); )(); 

Most of this is dictated by how a TinyMCE plugin is supposed to be coded, you can find some information about that in the TinyMCE documentation. For now, all you need to know is that the name of your button (pre_code_button) should be used in line 2 and 3. The value of "text" in line 4 will be displayed if you do not use an icon (we’ll take a look at adding icons in a moment).

The onclick method dictates what this button does when it is clicked. I want to use it to wrap selected text within the HTML structure discussed earlier.

The selected text can be grabbed using tinyMCE.activeEditor.selection.getContent(). Then, I wrap the elements around it and insert it, replacing the highlighted content with the new element. I’ve also added a new line so I can easily start writing after the code element.

If you want to use an icon I suggest selecting one from the Dashicons set which ships with WordPress. The Developer Reference has a great tool for finding icons and their CSS/HTML/Glyph. Find the code symbol and note the unicode underneath it: f475.

We’ll need to attach a stylesheet to our plugin and then add a simple style to display our icon. First up, let’s add our style to WordPress:

 add_action( 'admin_enqueue_scripts', 'pre_code_styles' ); function pre_code_styles()  wp_enqueue_style( 'pre_code_button', plugins_url( '/style.css', __FILE__ ) );  

Go back to the Javascript and next to the icon in the addButton function, replace “false” with a class you would like your button to have – I used pre_code_button.

Now create the style.css file in your plugin directory and add the following CSS:

 i.mce-i-pre_code_button:before  font-family:dashicons; content: "f475";  

Note that the button will receive the mce-i-[your class here] class which you can use to target and add styles. Specify the font as dashicons and the content using the unicode value from earlier.

Using TinyMCE Elsewhere

Plugins often create textareas for entering longer text, wouldn’t it be great if we could use TinyMCE there as well? Of course we can, and it’s pretty easy. The wp_editor() function allows us to output one anywhere in admin, here’s how it looks:

wp_editor( $initial_content, $element_id, $settings );

The first parameter sets the initial content for the box. This could be used to load an option from the database, for example. The second parameter sets the HTML element’s ID. The third parameter is an array of settings. To read about the exact settings you can use, take a look at the wp editor documentation.

The most important setting is the textarea_name. This populates the name attribute of the textarea element, allowing you to save the data easily. Here’s how my editor looks when used in an options page:

$settings = array( 'textarea_name' => 'buyer_bio' );
wp_editor( get_option('buyer_bio'), 'buyer_bio', $settings );

This is equivalent to writing the following code, which would result in a simple textarea:

<textarea id='buyer_bio' class='buyer_bio'><?php get_option( 'buyer_bio' ) ?></textarea>

Conclusion

The TinyMCE editor is a user-friendly way of allowing users more flexibility when entering content. It allows those who don’t want to format their content to just type it up and be done with it, and those who want to fiddle around with it to spend as much time as they need getting it just right.

Creating new buttons and functionality can be done in a very modular way, and we’ve only just scratched the surface of the possibilities. If you know of a particularly good TinyMCE plugin or use case which has helped you a lot, do let us know in the comments below!



Standard
Web design

Guide To Boosting Your Freelance Career With Pro Bono Work

People who are new to web design and development, writing or any other sort of creative work have little to show in their portfolio. And that’s a potentially major problem as thousands of experts with strings of portfolios are already out in a saturated market. What advantage could a newcomer have over someone who’s had years of experience and a reputation to boot?

Well, you can always go pro bono to build up your professional portfolio first. Want to know how? I’ve put together a quick guide on how to leverage pro bono work to gain more work.

What Is Pro Bono?

Pro bono is basically work done by a professional for free for the public. But in the freelance scene’s context, it’s for a freelancer’s image. Pro bono work is tricky. I say tricky because there are two different opinions on this. There’s the professionals who hate pro bono work and the ones who are for it.

The group against pro bono work feel that artists are getting ripped and selling themselves short of what they are worth. Alongside that you have many clients that prey on beginners to get free or extremely cheap labor.

The professionals are right; you should never ever sell yourself short. Hate on these predators (for lack of a better term) however you want, but why not you use them to your advantage instead?

The Sad Truth About Starting Freelancing

Only the experienced ones are given the high-paying projects. It doesn’t really matter if you are an experienced developer, designer or writer, if your online profile is basically zero, you’re out of luck.

You need to have an online presence.

When I started writing as a freelancer, 5 months after finishing university, no one wanted to work with me because I didn’t have any published articles online. I only started getting work because I did one free work. After which, I was recommended to and by people.

If you are new to the scene, I highly recommend selling yourself short (that’s a sentence I never thought I’d ever write). Suppose a project’s budget is around 00. If you think you can offer a 25-50% price slash, do it. If it’s a project that can be accomplished in just one day, you could even offer your services for free.

There is a catch though. Being the lowest bidder might give the impression that you are a low-quality worker. To turn this to your advantage, explain your situation: you are offering to work for less because you are new to the scene, but your client should expect no less than exceptional work.

Projects Worth Pursuing

Of course you shouldn’t just accept any project you see. You need to be meticulous and make sure that the project will potentially lead to other projects.

If you are looking for work on job boards like Elance, Freelancer, and the like, be sure to only talk to project owners with a robust history of projects. That way, you can ask them to contact you for future projects if they like your work.

Another thing you can do is to contact businesses or organizations in your area and offer your service. Try contacting the following in your locality; usually they have very little requirements and you’ll not get too much feedback (or additional input) and will be left on your own to do your magic. Plus, if you do it for free, you can always ask them to provide a good testimonial for you or to recommend you to others.

  • Schools
  • Churches
  • Orphanages
  • Interest groups
  • Your favourite local band
  • Your favourite restaurant
  • Politicians (if you are feeling adventurous)

When selecting your organization of choice, there are 3 important things to consider:

Is the organization connected with other organizations?

Organizations like to keep in contact with other similar organizations e.g. musician bands and indie groups know of other similar groups and if you were to make one website for one group, word may spread quickly of your services within the community.

Does it have a good image?

Where possible, you should steer clear from organizations with a bad image. Doing pro bono work should steer towards developing a positive image for yourself, not ruin it before it launches.

Is there potential for growth?

If the atmosphere suggests that the organization you’d want to work with has a great potential for growth, hop in without a second thought. You’ll be riding to the top with them as they popular and bigger.

Note that these are mere guidelines, not rules. You may prefer to work with individuals first instead of organizations. That’s fine too as it helps add to your ever-growing portfolio, giving you the boost you need in a different way.

How To Know What Works

A lot of companies and experienced freelancers do pro bono work on a regular basis. For example, web hosting companies do a lot of giveaways, offering a year’s worth of web hosting and domains for free. While they are not getting paid for their services, they are getting back free publicity. The same can be seen in graphic artists who release business card designs, logos, icons, fonts, artwork and the like on design blogs and creative outlets like Behance, Dafont, DeviantArt, and Dribbble.

Why does this work? People love free stuff. They will flock to you. And that’s the kind of publicity you want, a positive one. For web designers and developers, one effective method of driving people to your site is by giving away free website templates which, mind you, you can also include in your portfolio.

Do you see the trend here now? The gateway to success is basically to give your stuff for free at first, because if people loved your product or work, you will eventually be led to people who are willing to pay for more of your work.

Say No To spec Work

Urgh, spec work. Do not mistake pro bono work with… spec work. Unlike pro bono work which will probably get you leads to better-paying work in the future, spec work is just downright evil. It operates like this: the client behind a project will ask many individuals (mostly freelancers) to produce a work based on a specific list of requirements.

The bad news is, they pick, and pay, only the one result they want. After investing all that time and effort into producing spec work, you might leave empty handed, with no testimonial, publicity or leads to future project. Never engage in spec work — you’ll just encourage them to prey on other newcomers if you do.

Pro bono doesn’t only work for people who are just starting freelance work online. This also applies to seasoned freelancers who are experiencing "rainy days”, days when projects seem hard to come by. Start building your portfolio now. Remember, always move forward, even if it’s just one small step.

Standard
Web design

Guide To Boosting Your Freelance Career With Pro Bono Work

People who are new to web design and development, writing or any other sort of creative work have little to show in their portfolio. And that’s a potentially major problem as thousands of experts with strings of portfolios are already out in a saturated market. What advantage could a newcomer have over someone who’s had years of experience and a reputation to boot?

Well, you can always go pro bono to build up your professional portfolio first. Want to know how? I’ve put together a quick guide on how to leverage pro bono work to gain more work.

What Is Pro Bono?

Pro bono is basically work done by a professional for free for the public. But in the freelance scene’s context, it’s for a freelancer’s image. Pro bono work is tricky. I say tricky because there are two different opinions on this. There’s the professionals who hate pro bono work and the ones who are for it.

The group against pro bono work feel that artists are getting ripped and selling themselves short of what they are worth. Alongside that you have many clients that prey on beginners to get free or extremely cheap labor.

The professionals are right; you should never ever sell yourself short. Hate on these predators (for lack of a better term) however you want, but why not you use them to your advantage instead?

The Sad Truth About Starting Freelancing

Only the experienced ones are given the high-paying projects. It doesn’t really matter if you are an experienced developer, designer or writer, if your online profile is basically zero, you’re out of luck.

You need to have an online presence.

When I started writing as a freelancer, 5 months after finishing university, no one wanted to work with me because I didn’t have any published articles online. I only started getting work because I did one free work. After which, I was recommended to and by people.

If you are new to the scene, I highly recommend selling yourself short (that’s a sentence I never thought I’d ever write). Suppose a project’s budget is around 00. If you think you can offer a 25-50% price slash, do it. If it’s a project that can be accomplished in just one day, you could even offer your services for free.

There is a catch though. Being the lowest bidder might give the impression that you are a low-quality worker. To turn this to your advantage, explain your situation: you are offering to work for less because you are new to the scene, but your client should expect no less than exceptional work.

Projects Worth Pursuing

Of course you shouldn’t just accept any project you see. You need to be meticulous and make sure that the project will potentially lead to other projects.

If you are looking for work on job boards like Elance, Freelancer, and the like, be sure to only talk to project owners with a robust history of projects. That way, you can ask them to contact you for future projects if they like your work.

Another thing you can do is to contact businesses or organizations in your area and offer your service. Try contacting the following in your locality; usually they have very little requirements and you’ll not get too much feedback (or additional input) and will be left on your own to do your magic. Plus, if you do it for free, you can always ask them to provide a good testimonial for you or to recommend you to others.

  • Schools
  • Churches
  • Orphanages
  • Interest groups
  • Your favourite local band
  • Your favourite restaurant
  • Politicians (if you are feeling adventurous)

When selecting your organization of choice, there are 3 important things to consider:

Is the organization connected with other organizations?

Organizations like to keep in contact with other similar organizations e.g. musician bands and indie groups know of other similar groups and if you were to make one website for one group, word may spread quickly of your services within the community.

Does it have a good image?

Where possible, you should steer clear from organizations with a bad image. Doing pro bono work should steer towards developing a positive image for yourself, not ruin it before it launches.

Is there potential for growth?

If the atmosphere suggests that the organization you’d want to work with has a great potential for growth, hop in without a second thought. You’ll be riding to the top with them as they popular and bigger.

Note that these are mere guidelines, not rules. You may prefer to work with individuals first instead of organizations. That’s fine too as it helps add to your ever-growing portfolio, giving you the boost you need in a different way.

How To Know What Works

A lot of companies and experienced freelancers do pro bono work on a regular basis. For example, web hosting companies do a lot of giveaways, offering a year’s worth of web hosting and domains for free. While they are not getting paid for their services, they are getting back free publicity. The same can be seen in graphic artists who release business card designs, logos, icons, fonts, artwork and the like on design blogs and creative outlets like Behance, Dafont, DeviantArt, and Dribbble.

Why does this work? People love free stuff. They will flock to you. And that’s the kind of publicity you want, a positive one. For web designers and developers, one effective method of driving people to your site is by giving away free website templates which, mind you, you can also include in your portfolio.

Do you see the trend here now? The gateway to success is basically to give your stuff for free at first, because if people loved your product or work, you will eventually be led to people who are willing to pay for more of your work.

Say No To spec Work

Urgh, spec work. Do not mistake pro bono work with… spec work. Unlike pro bono work which will probably get you leads to better-paying work in the future, spec work is just downright evil. It operates like this: the client behind a project will ask many individuals (mostly freelancers) to produce a work based on a specific list of requirements.

The bad news is, they pick, and pay, only the one result they want. After investing all that time and effort into producing spec work, you might leave empty handed, with no testimonial, publicity or leads to future project. Never engage in spec work — you’ll just encourage them to prey on other newcomers if you do.

Pro bono doesn’t only work for people who are just starting freelance work online. This also applies to seasoned freelancers who are experiencing "rainy days”, days when projects seem hard to come by. Start building your portfolio now. Remember, always move forward, even if it’s just one small step.



Standard