Monthly Archives: October 2013

How to Add Social Media Icons to Your Blog

One of the must have blog item is to ease the access to your social media platforms for your reader, e.g., Facebook, Twitter, Pinterest, etc. Which makes it easy for your reader to connect with you.

Some theme may have those facility in widget such that you can enable it and add your information. In case it doesn’t, this tutorial explains how to add social media icons to your WordPress. You can add it to anywhere you like.

Here, we don’t use icon, instead we use Genericons font pack.  Genericons is a set of very clean, vector-based icons embedded in a webfont, which can be scaled to any resolution, or even styled with CSS.  Genericons is an efficient way to display icons on your site without increasing load times. They also allow for quick and simple styling without the use of an image editing program.

  1. As usual, always start off by using a child theme.
  2. Install Genericons.
    In WordPress, you can use the  Genericon’d plugin.
    Or you can download the zip file manually.  Then extract the files and upload the fonts folder to your child themes directory, e.g., /MAMP/myDemo3/wp-content/themes/twentytwelve-child/
  3. Add following into your style.css
    /************************************************/
    /* Using Genericons */
    /************************************************/
    @font-face {
    font-family: 'Genericons';
    src: url('font/genericons-regular-webfont.eot');
    src: url('font/genericons-regular-webfont.eot?#iefix') format('embedded-opentype'),
    url('font/genericons-regular-webfont.woff') format('woff'),
    url('font/genericons-regular-webfont.ttf') format('truetype'),
    url('font/genericons-regular-webfont.svg#genericonsregular') format('svg');
    font-weight: normal;
    font-style: normal;
    }
    /*SOCIAL ICONS*/
    .social-block a:before {
    font-family: ‘genericons’;
    speak: none;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;
    font: normal 24px/1 ‘Genericons’;
    -webkit-font-smoothing: antialiased;
    }
    .icon-google:before {
    content: “\f206″;
    }
    .icon-facebook:before {
    content: “\f204″;
    }
    .icon-twitter:before {
    content: “\f202″;
    }
    .icon-feed:before {
    content: “\f413″;
    }
    .icon-flux:before {
    content: “\f413″;
    }
    .icon-github:before {
    content: “\f200″;
    }
    .icon-dribbble:before {
    content: “\f201″;
    }
    .icon-pinterest:before {
    content: “\f209″;
    }
    .icon-youtube:before {
    content: “\f213″;
    }
    .icon-linkedin:before {
    content: “\f208″;
    }
    .icon-wordpress:before {
    content: “\f205″;
    }
    .icon-instagram:before {
    content: “\f215″;
    }
  4. Then, put in the related html code into the text area.  For example, I added following into a widget:
    131011m

And the widget will looks like:

131011n

 

References

How To Install & Display Genericons

Password Protect Zip Files in Mac OS X

If you’re familiar with the command line, the syntax of the encrypted zip command is as follows:
zip -er [archive] [file]

The -e option means encrypt the archive; the -r option tells the command to travel the directory structure recursively.  These encrypted zip files will maintain password protection across platforms, meaning you can send a protected zip file to a Windows user and they will still need to enter the password in order to view the contents.

Customise WordPress: environment

get_template_part

Assuming the theme folder is wp-content/themes, that the parent theme is twentyten, and the child theme is twentytenchild, then the following code –

get_template_part( 'content', get_post_format() );

that will look for files like content-link.php, content-gallery.php and so on.  In fact, it will do a PHP require() for the first file that exists among these, in this priority:

  1. wp-content/themes/twentytenchild/content-link.php
  2. wp-content/themes/twentyten/content-link.php
  3. wp-content/themes/twentytenchild/content.php
  4. wp-content/themes/twentyten/content.php
  5. wp-content/themes/twentyten/index.php

Now, imagine you’re working on a child theme. You created content.php and content-gallery.php. You expect gallery posts to pick up content-gallery.php, which is correct.

You also expect a link post to pick up your content.php file because there is no content-link.php in your child theme, right? This is also correct, unless your parent theme has a content-link.php file, which will be of higher priority to the template loader, despite the child-parent relationship between the two themes.

It does make sense, otherwise a simple index.php file in your child theme would override all of the parent theme’s templates, because index.php is a fallback for everything. That would render child themes useless.

To use this function with subfolders in your theme directory, simply prepend the folder name before the slug.  For example, if you have a folder called “partials” in your theme directory and a template part called “content-page.php” in that sub-folder, you would use get_template_part() like this:

get_template_part( 'partials/content', 'page' );

PHP Basics for WordPress Newbies

It is assume you already know at least one  programming language.

Function

Start with the simplest function possible example, the classic “hello world”.

1
2
3
4
5
function hello_bacon(){
  echo “hello bacon”;
}
hello_bacon(); // prints: hello bacon

Sample function that returns a value.

1
2
3
4
5
function hello_bacon(){
   return “hello bacon”;
}
hello_bacon();

To print it later we’d have to actually echo out the function.

1
echo hello_bacon();

or

1
2
$hello = hello_bacon();
echo $hello; // prints: hello bacon

Getting into Arguments

Example on sending variables into functions as arguments.

1
2
3
4
5
6
function favorite_food($food){
   echo 'My favorite food is ' . $food;
}
favorite_food(); //prints: My favorite food is <--didn't pass an argument so $food is empty, and I'm hungry.
favorite_food('guacamole'); //prints: My favorite food is guacamole

As you can see above, the favorite_food() function accepts 1 argument. Inside of the favorite_food() function, this argument will be referred to by the variable $food.

1
2
favorite_food('guacamole'); //still prints: My favorite food is guacamole
echo $food; //nothing doing

If you need to ensure that you never get an empty value for “My favorite food is ____” then you can give an argument a default. If you don’t pass an argument when calling a function it will simply use the default. Note below that ‘bacon’ is the default value of the $food variable.

1
2
3
4
5
6
function favorite_food($food = 'bacon'){
   echo 'My favorite food is ' . $food;
}
favorite_food(); //prints: My favorite food is bacon
favorite_food('guacamole'); //prints: My favorite food is guacamole

By now you might have noticed that we’ve only been dealing with ‘string’ variable.  You’ve been seeing me combine strings together with a period (.) in what is called string concatenation.

1
2
3
4
5
6
7
function double($x){
   return $x * 2;
}
$a = 10;
$a = double($a);
echo $a; //prints: 20

Variable Scope

Variables usually only exist inside the function where they are defined.  In PHP and WordPress you can declare variables as global in scope, meaning $x has the same value everywhere.  By default, variables are local in scope.

For the above example, the $x in the double() function is not the same as the $a outside of it.  Variables are just placeholders.  In the following line:

1
$a = double($a);

We are passing a value to the double() function. The function then catches the value as its argument.

1
function double($x)

Now the variable has a new name, but the same value. In the example the value was 10, that part isn’t any different. Within the function the variable $a now has a value of 10. Then it performs its multiplication and sends back the doubled value.

1
return $a *2;

And that brings us back to:

1
$a = double($a);

where the variable $a catches the return value, and the variable $a is now equal to 20, which we see when we echo $a.

There is the official PHP manual:

http://php.net/manual/en/language.variables.scope.php

Customise WordPress: hook, filter

First you need to understand how filters and action hooks work, you will see these questions really all follow the same pattern. You just need to learn how to speak WordPress ! Be patient with yourself, because you literally are learning a new language … especially if you aren’t already familiar with PHP.  I will be using examples for working with the  Thematic Theme Framework.

What is an Action Hook

Action hooks look like this:

1
do_action('action_hook_name');

In a plugin such as WooCommerce, if you investigate in the templates folder you will find all sorts of action hooks. The WooCommerce templates are extremely well-documented and tell you right there which functions are hooked into that action hook and in what order. In the theme, Thematic most of these are buried in the library/extensions folder.  In fact, in the actual templates (like index.php, category.php etc) you will see hooks that look more like:

1
2
// action hook for placing content above the index loop
 thematic_above_indexloop();

But if you go searching for the definition of that function you will find that it is in content-extensions.php

1
2
3
4
5
6
7
8
9
/**
 * Register action hook: thematic_above_indexloop
 *
 * Located in index.php
 * Just before the loop
 */
function thematic_above_indexloop() {
 do_action('thematic_above_indexloop');
} // end thematic_above_indexloop

Now an action hook is sort of like a parking spot. Some are empty, some have cars on them. you can move the cars around, but the spots themselves stay put. When wordpress gets to an action hook, it will run all the functions that are attached to that particular hook. If it gets to a parking spot and finds a car, it will run that car. If not, then it will continue on to the next hook.

How to add function to a hook

A completely fictitious example:

1
2
3
4
function function_you_want_to_add(){
echo "I heart bacon!";
}
add_action('destination_hook','function_you_want_to_add', $priority, $args );

The add_action line always takes this “form”, it means: add the function called ‘function_you_want_to_add’ to the hook called ‘destination_hook’ in the order of $priority with optional  arguments $args.

You can read all about add_action in the WordPress Codex.

The $priority is always a number. It is like a traffic cop in the parking lot, or maybe just an orange cone. If more than 1 function wants to be on a particular hook the priority decides which goes first. If 2 cars wanted to be in the same spot, the one with the lower number priority would get ground level parking and the one with the higher priority would be stacked on top.  The default priority is 10, so if you don’t need to change that you don’t even need to define it in your add_action line.

Some hooks pass additional variables to the functions that operate on them.

A practical example:

1
2
3
4
function function_you_want_to_add(){
echo "I heart bacon!";
}
add_action('thematic_above_indexloop','function_you_want_to_add');

If you add the example to your child theme’s functions.php you will see “I heart bacon!” appear on your blog page. Now leave that there and add the following just underneath it in your functions.php.

1
2
3
4
5
function kia_another_function(){
echo "Guacamole makes me happy!
";
}
add_action('thematic_above_indexloop','kia_another_function', 5);

Notice the priority number is 5. This means it has a lower priority number than the first function, which is 10 by default since we didn’t specify anything. When you reload your theme you should now see Guacamole makes me happy! on the blog index above the line about loving bacon. Bacon and guacamole together. It must be code heaven.

Removing a Hook

Removing stuff works a bit differently:

1
2
3
4
function remove_stuff(){
remove_action('hook_location','function_you_want_to_remove',$priority );
}
add_action('init','remove_stuff');

It tells WordPress, when it runs the init hook, please remove the function called “function_you_want_to_remove” that is located on the hook called “hook_location” with a priority of $priority.

init is just a WordPress hook. It is one of the earliest hooks that run when WP starts whirring. You can see most of the hooks that run in the WordPress process again at the Codex: Action Hooks . To remove something that had a specific priority originally, you must remove_action it with the same priority.  A good practical example would be removing the Thematic blog title.

1
2
3
4
function remove_thematic_header(){
remove_action('thematic_header','thematic_blogtitle', 3);
}
add_action('init','remove_thematic_header');

Paste the above into your functions.php, reload your child theme and poof the blog title is gonzo!

Moving the #access menu is another practical example, that combines adding and removing functions.  I’ll include it here because I see this question asked all the time.

1
2
3
4
5
function remove_thematic_header(){
remove_action('thematic_header','thematic_access', 9);
}
add_action('init','remove_thematic_header');
add_action('thematic_aboveheader','thematic_access');

Note that we don’t have to define thematic_access, because it already is defined by thematic. We can simply add_action it to a new parking spot.

Overrides

Thematic has a bunch of functions built in that if you define them, they automagically replace the function thematic was going to add to a specific hook, with your custom function.  In WordPress parlance, this is called a pluggable function.  Many thematic functions can be overridden by copying a thematic function to your functions.php and altering the function’s prefix from thematic_ to childtheme_override_.  The overrides completely change the car that is parked on a particular parking spot but they don’t change its location.

For instance to override the thematic_blog_description you could put the following in your functions.php

1
2
3
function childtheme_override_blogdescription(){
echo "Evil laugh! Now your blog is only about bacon!";
}

Refresh your theme and you will see the blog description has been taken over by bacon, which I think is neat.  Note that with pluggable functions you do notneed to also call add_action.  Doing so will add the function twice.  Most functions in thematic have this override capability, but not all.  You can browse through the extensions folder (look but don’t touch the parent theme!)

If you see something like:

1
if ( function_exists('childtheme_override_blogdescription') )

That’s a sign that you can use the override feature.  The full IF statement means: if you defined a child_theme_override function then Thematic will add your custom function to the appropriate hook instead of its own function.

Overrides are significantly more intuitive than filters, but filters can be more elegant.

Filter

A filter is like a magic function box that takes a value in ( remember I talked about parameters in by Basics tutorial ) do something with it and send it back. So you have a red Porsche on the lot, send it to a filter and it might become a blue Porsche. Or a black pickup truck. Whatever. But it will still be parked in the back, 2 spots from the end.

When browsing WordPress core, themes and plugins, you will be alerted to the availability of a filter by the appearance of the apply_filters() function. In generic terms it will look like so:

1
apply_filters( 'name_of_target_filter', $variable_getting_filtered, #priority, $other_arg );

It might look like:

1
return apply_filters( 'name_of_target_filter', $variable_getting_filtered, #priority, $other_arg );

or:

1
echo apply_filters( 'name_of_target_filter', $variable_getting_filtered, #priority, $other_arg );

or even:

1
$variable_getting_filtered = apply_filters( 'name_of_target_filter', $variable_getting_filtered, #priority, $other_arg );
Parameters for the Filters

The big tip off is the apply_filters() function, it can take an unlimited number of parameters but only the first two are required.

1. The first is the name of the filter. I was very confused early on because the Thematic framework tended to name the filters the same thing as the functions that contained them. And then in the one instance where they were difference, I couldn’t get my filter to work for anything. I swore and through things, cried and shaved a few days off my life from the stress. Turns out their sharing names was a convenience factor that makes a lot more sense to me now. So, just remember that first parameter is the filter’s name.

2. This is an important one, because this parameter is the variable that your function will receive. This is the value we’re going to change.

3. This it the priority. Just like with adding functions to hooks, this controls the order that filter functions will be applied should there be more than one. The default is 10, so if you need your filter to run before that you’d use a lower number. This is rare, and usually you need to run your filters after others, so you’d want to use a higher number. In fact, until you are sure that you are conflicting with another function you can pretty much just leave it at 10.

4+. These are other variables that might give you some useful information for manipulating the variable getting filtered. Remember we talked about scope in the PHP Basics. Instead of declaring these globally and hoping they arrive intact, WordPress will send your filtered variable along with some friends.

A Filter with Training Wheels

In super generic terms let’s take a look at the basic set up for filtering.

1
2
3
4
5
6
7
8
9
function sample_filter_function( $in_from_function, $other_arg ) {
$out_to_function = $in_from_function . " add some bacon here!";
return $out_to_function;
}
add_filter('name_of_target_filter','sample_filter_function', #priority, 2 );

The structure is almost same as add_action(). In reality, we are adding an action, just of a slightly different type: one that modifies a specific variable’s value. One thing to note here, is the number 2. This is the number of parameters that you are passing into the function. You’ll always pass 1 variable ( ie. the variable that you are filtering) and in this case you wouldn’t even need to declare it. That’s the default value, just as 10 is the default value for #priority. However, some filters provide access to other variables (like our fake $other_arg), and if you want to use them in your filter function then you have to name them inside the parentheses and then write the correct number at the end of the add_filter() statement.

If you have 2 parameters in the function, but don’t have the number 2 at the end of add_filter() you will get White Screen of Death. If you have the number 2, but don’t declare two parameters, guess what, you will also get WSOD. So make sure your parameters match up.

And you must return a value. If you do not, that is essentially the same as returning a null string. If you echo something here, it will likely not appear where you expect it, so don’t. RETURN, RETURN, RETURN. Remember in my PHP basics I talked about two functions playing catch. The return statement, is you throwing your modified version of the variable back to the apply_filters() function so that WordPress can continue on its merry way, but using your value now.

I want to end on a real filter that you can drop into your theme’s functions.php and actually see a working result.

1
2
3
4
5
6
7
8
9
function kia_the_title( $title ) {
$title .= " BACON!";
return $title;
}
add_filter('the_title','kia_the_title' );

Not too shockingly I am using Bacon in my testing code. If this bothers you…. well, its just code. WordPress has a filter called the_title() that lets you modify the title of every post! As written above it will literally add BACON everywhere the_title() is called. Following example will only add Bacon to the titles in the main loop, and only on the front-end.

1
2
3
4
5
6
7
8
9
10
11
12
13
function kia_the_title( $title ) {
if ( ! is_admin() && is_main_loop() ) {
$title .= " BACON!";
}
return $title;
}
add_filter('the_title','kia_the_title' );

 

References

A Newbie’s Guide to WordPress Hooks and Functions

Thematic Page Structure

Visualizing Thematic 4 You

http://thematicmondo.com/directory/resources-tutorials/

Customising wooCommerce

The template files of WooCommerce contain the markup and template structure for the front-end of your store. They contain many hooks which allow you to add / move content without having to edit the template files themselves. This method protects even further against any upgrade issues as the template files can be left completely untouched.

Do not edit these files within the core plugin itself as they are overwritten during the upgrade process and any customisations will be lost.  Instead, you should edit these files in an upgrade safe way through overrides. Simply copy it into a directory within your theme named /woocommerce, keeping the same file structure.

Example: To overide the admin order notification, copy:
wp-content/plugins/woocommerce/templates/emails/admin-new-order.php to
wp-content/themes/yourtheme/woocommerce/emails/admin-new-order.php

The copied file will now override the WooCommerce default template file.

See woocommerce plugin, Template Structure + overriding templates via a theme for the  template files which are found within the /woocommerce/templates/ directory.  Alternatively, you can simply navigate to the plugin you have downloaded and check them out.

You can edit and override any file within the woocommerce template directory using that method.  Rearranging some elements around may require actions and hooks within a functions.php file. I have created a file called functions-custom-woocommerce.php to separate my WooCommerce customisations.  In turn, I need to call it from the main functions.php file.  Add following lines to the beginning of the functions.php file:

/*---Include WooCommerce Custom Functions File*/
include_once (get_stylesheet_directory() . '/functions-woocommerce-custom.php');

Customise wooCommerce: remove shipping calculator from cart page is an example of customizing WooCommerce using the method of overriding template files.

One way to learn how customisation is by looking at themes using wooCommerce.  Browse to the theme directory and search for the string “woo”, e.g., in Mac OS X (Unix), you can:

grep -R woo *

Typically, you should find out there are codes in the functions.php which detect and divert the setting in another file for customisation.

if ( class_exists( 'woocommerce' ) ) {
functions.php: require_once( trailingslashit ( THEME_DIR ) . 'includes/functions/theme-woocommerce.php' );

A

Customise wooCommerce: remove shipping calculator from cart page.

In this example, your company offers free shipping, so you want to remove the shipping calculator from cart page.  The default layout is like:

131008p

And you don’t need the “Calculate Shipping” anymore.  What you need to do is:

  1. Create a woocommerce directory in your theme at the root if you haven’t already.
  2. Go to the woocommerce plugin folder under your site
    wp-content/plugins/woocommerce/templates/cart
  3. Find the cart.php template file.
  4. Copy that file to your woocommerce directory within your theme under the directory path (woocommerce/cart/cart.php) – Meaning you have to have a folder of cart within the woocommerce folder.
  5. This copy of cart.php now overrides the file in the plugin directory.
  6. Look at the bottom of the cart.php file that you are now editing. At the very bottom is the following code:

    131008q
    The part that says woocommerce_shipping_calculater can be moved around.

  7. Remove the woocommerce_shipping_calculater line.
Result:

131008o

Customise wooCommerce: move your title to above the thumbnail in product page.

In your product page, if you want to move the product title from

131008m

to

131008n

In this example, we want to move the product title out of the summary section and position it above the main product image or somewhere at the top of the page.  We need to look at the content-single-product.php template file.  Here are the two sections we we need to look at in that file:

131008r

The part that outputs the main product image is woocommerce_before_single_product_summary

The part that outputs the product title is woocommerce_single_product_summary

Let’s pull the title out of the summary block and place it in the block that precedes it so the product title is above the product images.  So, place this in your functions.php file or the custom functions file.

/*---Move Product Title*/
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_before_single_product_summary', 'woocommerce_template_single_title', 5 );

See also Customising wooCommerce for more hints in how to organise these settings.

References

Most basic customisation seems impossible

Resize photo to larger size

Most people know to use software to adjust a photo to smaller size, or larger compression ratio, in order to reduce the file size.  Sometimes, we need do it the other way around, i.e., to adjust tolarger dimension. For example, to upload a picture to some sites, they may require that your pixel size can not be too small.

Freeware ImageMagick have this feature. Use the convert command in this package, you can convert image to larger size. There are several options to achieve the above aims:

-sample
-resample
-scale
-resize
-adaptive-resize
-thumbnail

resize

Example, -resize 400x300+20+30 (like the -scale and -sample) converts an input to an output image with pixel dimensions of 400x300. The +20+30 shifts the output by 20 pixels to the right and by 30 pixels to the bottom. There are a few differences to -scale:

  • -resize does support an additional setting of -filter (which should occur on the commandline before using -resize!).
  • -filter determines the exact algorithm to be used for the colors of added pixels in the case of magnification, or for the colors to be used for the remaining pixels when some of their neighbors are removed in case of reduction.
  • For a list of supported filters, simply run convert -list filter.
  • -filter point -resize 400x300 creates exactly the same result as -sample 400x300, but it runs still a bit slower.
  • If not set alongside (before) -resize, the conversion will silently default to -filter Lanczos which is slower, but which generates a much better quality (because it takes into account the colors of all surrounding pixels for any newly added ones) than -filter point produces (which uses the nearest neighbor rule to determine the color of a newly added pixels).

sample

Example, -sample 400x300 converts an input image to an output images which has the pixel dimensions of 400x300.  The differences to -resize:

  • -sample does not support additional setting of -filter-filter is simply ignored.
  • When magnifying (the input image size smaller than 400x300), pixels are replicated in blocks.
  • When reducing (the input image size larger than 400x300), pixels are sub-sampled with a very simple algorithm: some rows and columns are simply skipped over.
  • The geometry argument to -resize doesn’t support any offset part.
  • The output will never have more (different) colors than the input image had; it may have fewer colors though.

Therefore -sample is faster than -resize, but output quality is usually worse: you can easily get extreme blocking and aliasing effects in the resulting output.

scale

Example, -scale 400x300 produces the equivalent result (but is faster, because it avoids all the filter processing) as does using -filter box -resize 400x300. It also ignores any current -filter setting.

  • When reducing, it changes the image size simply by replacing pixel colors by averaging the respective input pixel colors together.
  • When magnifying, it simply replicates the respective input pixels for the required additional pixels.

adaptive-resize

Example, -adaptive-resize 400x300 does not support the offset part of geometry parameter and also ignores the -gravity setting.

  • It uses by default data-dependent triangulation when resizing (unless the resize method is overridden by additionally specifying -filter [something]).

thumbnail

Example, -thumbnail works just like -resize does, with a few differences:

  • It is optimized for speed.
  • It also removes any embedded color profiles to reduce the filesize of the thumbnails.
References

What the difference of sample/resample/scale/resize/adaptive-resize/thumbnail ImageMagick convert?

ImageMagick crop command not giving perfect result