Archive for the ‘Wordpress’ Category

Customising wp_nav_menu()

Friday, November 2nd, 2012

Ever wanted to use the convenient built-in menu support of WordPress, but been frustrated or confused by the inflexibility of the wp_nav_menu() structure? WordPress actually allows much deeper customisation when you dig a little deeper, with its custom Walker functions.

For minor customisations, such as removing the navbar’s container, wp_nav_menu has an array of options that can be passed to it which makes the task quite simple. For adding a css class to specific links in the navbar, you can use WordPress’s powerful ‘add_filter’ functionality. The shortcomings of these methods, though, is that they don’t offer a way to manipulate the actual order or structuring of the unordered list itself – in order to put in an extra <li> with a subheading, for instance, you’d need to resort to javascript or empty ‘custom links’ in the menu interface.

To allow control of this sort of thing, WordPress allows to you create customised ‘walker functions’. WordPress actually uses these functions to handle many of its looping structures – pages, categories, comments, and more. A great introduction for editing these other kinds of structures can be found here.
The walker function I’m going to be focusing on, though, is the WP_Nav_Walker function, located in wp-includes/nav_menu_template.php around line 174. Remember, though, as with Magento, you should never edit core files, because if you upgrade to the latest version of wordpress in the future, your customisations may be overwritten. Instead copy all the code for the Walker_Nav_Menu, go to your functions.php file, and paste it in there. Change Walker_Nav_Menu to your whatever you’d like, i.e. mytheme_nav_walker, and change ‘extends Walker’ to ‘extends Walker_Nav_Menu’.
Now you have a copy of the walker function that you can edit to your heart’s content. A good explanation and an example on editing this file can be found in the wordpress codex, at http://codex.wordpress.org/Function_Reference/wp_nav_menu#Using_a_Custom_Walker_Function. This example shows you how to add conditional classes based on the ‘depth’ (for submenus). It overrides start_lvl() (called each time the walker encounters a new submenu), end_lvl() (called at the end of each submenu), start_el() (called for each item) and end_el() (called at the end of each item). As you can tell by looking at them, end_lvl() and end_el() are quite simple in themselves, merely adding a closing <ul> or <li> tag after indenting the code (for readability). Note that if you want to edit these functions, you should copy the original from nav_menu_template.php (as you have done) and edit that, since you don’t want to make it from scratch but simply modify it.
This example is great, but it didn’t tell me everything I needed to know. I wanted to take a wp_nav_menu, and wraps the links in groups of 3 without simply making a submenu and using ‘position: absolute’ to force a layout, like so:Screen shot 2012 11 02 at 11.13.211 Customising wp nav menu()
I also didn’t want to hard-code the menu; as it was for a CMS site, I wanted them to have a certain amount of control over it.
So I needed a way to keep track of how many elements had been processed – I needed access to the function actually controlling the loop, so I could have a counter. After a bit of digging, I found this: http://codex.wordpress.org/Function_Reference/Walker_Class. This showed a ‘walk()’ function, that did exactly what I wanted, but looking in nav_menu_templates.php, I could see no reference to it at all. This was a problem, since (as mentioned earlier) I needed to copy the original function, and edit it. I searched through wp-includes until I found the function in class-wp-walker.php – this is the base walker class that all the other WordPress Walkers (including the Walker_Nav_Menu class we’re editing) inherit. I copied the walk() function into my functions.php, inside my custom class with the other functions. Here’s my edited function:

function walk( $elements, $max_depth) {
		$args = array_slice(func_get_args(), 2);
		$output = '';
		$counter = 1;
		if ($max_depth < -1) //invalid parameter 			return $output; 		if (empty($elements)) //nothing to walk 			return $output; 		$id_field = $this->db_fields['id'];
		$parent_field = $this->db_fields['parent'];
		// flat display
		if ( -1 == $max_depth ) {
			$empty_array = array();
			foreach ( $elements as $e )
				$this->display_element( $e, $empty_array, 1, 0, $args, $output );
			return $output;
		}
		/*
		 * need to display in hierarchical order
		 * separate elements into two buckets: top level and children elements
		 * children_elements is two dimensional array, eg.
		 * children_elements[10][] contains all sub-elements whose parent is 10.
		 */
		$top_level_elements = array();
		$children_elements  = array();
		foreach ( $elements as $e) {
			if ( 0 == $e->$parent_field )
				$top_level_elements[] = $e;
			else
				$children_elements[ $e->$parent_field ][] = $e;
		}
		/*
		 * when none of the elements is top level
		 * assume the first one must be root of the sub elements
		 */
		if ( empty($top_level_elements) ) {
			$first = array_slice( $elements, 0, 1 );
			$root = $first[0];
			$top_level_elements = array();
			$children_elements  = array();
			foreach ( $elements as $e) {
				if ( $root->$parent_field == $e->$parent_field )
					$top_level_elements[] = $e;
				else
					$children_elements[ $e->$parent_field ][] = $e;
			}
		}
		foreach ( $top_level_elements as $e )
		{
			if ($counter >=4)
			{
				$counter = 0;
				$output .= "</ul>\n";	
			}
			//start new list if necessary
			if ($counter == 0)
			{
				$counter++;
				$output .= "<ul class='menu'>";
			}
			$this->display_element( $e, $children_elements, $max_depth, 0, $args, $output );
			$counter++;
		}
		/*
		 * if we are displaying all levels, and remaining children_elements is not empty,
		 * then we got orphans, which should be displayed regardless
		 */
		if ( ( $max_depth == 0 ) && count( $children_elements ) > 0 ) {
			$empty_array = array();
			foreach ( $children_elements as $orphans )
				foreach( $orphans as $op )
					$this->display_element( $op, $empty_array, 1, 0, $args, $output );
		 }
		 return $output;
	}

The changes I made were relatively simple – at the beginning of the function, I initialised my counter: ‘$counter = 1;’
Then, I edited the foreach loop that handled the top-level elements (as I only wanted to split those, and leave submenus untouched):

foreach ( $top_level_elements as $e )
		{
			if ($counter >=4)
			{
				$counter = 0;
				$output .= "</ul>\n";	
			}
			//start new list if necessary
			if ($counter == 0)
			{
				$counter++;
				$output .= "<ul class='menu'>";
			}
			$this->display_element( $e, $children_elements, $max_depth, 0, $args, $output );
			$counter++;
		} 

The display_element function is the function that calls start_lvl, end_lvl, start_el, and end_el, as necessary. Each time it runs for the top level elements, I’ve simply incremented it, and for every 3rd element, I’ve closed off the list and opened a new one on the next iteration. The reason I do this in the following iteration and not at the end of the current one is to prevent extra </ul> tags
So that’s the editing done. Remember, you can remove start_lvl(), etc., from functions.php if you’re not editing them – your class will just inherit the default from nav_menu_temlate.php. So how do you use it now? Well, that’s the easy part. In my template:

<?php wp_nav_menu( array('menu' => 'Footer Nav', 'walker' => new mytheme_walker_nav_menu )); ?>

Using wordpress template hierarchies to control CMS sites

Friday, October 19th, 2012

If you’ve ever made a content manageable site for a less technically-savvy client, then chances are you’ve used custom templates. You’ll probably have one for the home page, and one for the content pages, and maybe one for the contact page. But what if the client wants to add a new page, and they use the wrong template? Hopefully they’ll realise quickly, and change to the appropriate template.
Some larger sites, however, end up having many layouts, and therefore many custom template, and they can become confusing to some users. This highlights the importance of naming your templates clearly and descriptively. It can help, though, to trim down the number of custom templates available to the client in the first place.
This can be done by utilising the template hierarchy built into wordpress. The full list can be found here: http://codex.wordpress.org/Template_Hierarchy
This structure means that say, for instance, the home page (which is a static page) is going to have a unique layout complete with calls to action, etc, which don’t need to show up on any other pages. Instead of making a custom template file, you simply create home.php and fill it out exactly like you would the template page – just leaving out the Template Name comment at the top of the file. Now, you create the Home page inside the wordpress admin area, leave the template on ‘default’, and publish it.
When somebody visits your site wordpress automatically searches for the home.php file and applies it only to the home page. Any other pages will still use (for the time being) the index.php template. So, now you’ve created a custom template that the client does see, or need to see.
The same can be done for every other page by using either page-{slug}.php or page-{id}.php (e.g. page-contact.php). Personally, I would advise using the page id, as the user may change the page slug (if, for instance, they change the page name to contact us instead of contact). If you want to make it bullet-proof, you could always use both, though I’ve never found that necessary.
Make sure that page.php (the default page template) is styled as well, as any new pages the client adds will look like this one (since they won’t have their own page-{ID}.php).
This method is not just for pages, though. A quick look at the hierarchy shows that it can be done for archives, custom posts, categories, etc. If you want a particular category of posts to show up differently, category-{slug} or {id}.php will control that for you, with any categories that don’t have their own file automatically falling back to archive.php by default. The same goes for custom posts (though these MUST use single-{post-type}.php
But what if you want posts from a certain category to have their own single.php? At the moment, WordPress doesn’t support this very well, but there’s a good workaround if these posts are only going to be part of one category.
Firstly, create your single-{category-id} or {category-slug}.php files, as well as a single-default.php. Then, open single.php, clear it out, and paste the following php:

$post = $wp_query->post;
if ( in_category('11') ) {
include(TEMPLATEPATH . '/single2.php');
} else {
include(TEMPLATEPATH . '/single-default.php');
}

Replace the ’11′ with the appropriate category id (which can be found by going to posts>categories>your-category in the wordpress admin area, and looking at the address bar). The above can be extended with as many else if lines as necessary, but make sure you always include else { include(TEMPLATEPATH . ‘/single-default.php’); } at the bottom!

Using this templating solution, the only time you really need to use page templates is when you want to give the client a choice of layouts (such as sidebar on the left, or sidebar on the right). This will result in much less confusing template choices for the client, and hopefully, less chance of them breaking the site you’ve made. Always ensure, though, that the default templates 1) exist and 2) have been styled!

Google Penguin Update for Small Businesses

Tuesday, July 31st, 2012

The SEO has been hit by Google’s penguin update especially small businesses which are already having a bad time due to the current economic climate. Many websites have had SEO companies use a lot of black hat technics which have been penalised many businesses across the board. If you are a businesses owner reading this or a web master then there are a few thing which you can do or change to help you crawl back up.

Firstly blogging via RSS and social media signals are very important hence blog regularly especially on places such as Google Plus and it is important to create yourself a Google Plus Page with your business information and website details. Twitter, Facebook and Linkedin accounts are also important to obtain. Here at Web Design GM have found a neat trick which connects your RSS or WordPress blog with your three main social media signals and allows your blog to be posted throughout your Social Media accounts. Twitterfeed is a simple to use and you do not need to install anything all you need to do is follow the few easy steps and connect your RSS blog to your social media signals. Google Plus does not currently support having your WordPress blog being pushed to it but it may eventually allow it overtime.

Make sure all of your content is unique and not copied from another website. This is very important as Google regards content as king, so good quality content is essential for SEO and content which is not too spammy (keywords not all over the place). Try to make the content natural as possible so it reads good and explains what your business is really about. Make sure all spelling mistake and grammar is checked before your content is added to your website.

Interlink only a few keywords on other pages but with the new update variation is key. So for example if double glazing is my keyword then I will have links for a variation of this keyword on other pages e.g. uPVC windows. It is important you try not to have the keyword linked all over the place as Google will penalise you for this now. On this note, try not to have keywords in the footer as well. The footer should only be used for usability and not for SEO purposes so have your site maps here and other web pages but no keywords please.

Don’t have spammy title or meta tags and try not to over do the meta keyword tag as Google will not look at this in great depth nowadays.

If your a business who has local SEO add your website to local directories e.g. Bristol business directories or Cardiff business directories which will certainly help your SEO campaign once Google has cached these pages. Some good business directories to add your website to could be Touch Local, Thompson Local just basically Google “your areas business directory”.

Any questions or tips you might need please do not hesitate to contact us on 02920 290 080 or 01179 000 482.

Adding a custom widget area in WordPress

Friday, June 29th, 2012

I am currently developing a CMS website for one of our clients. My aim is to make every element of their site editable for them, meaning they can amend any element on any given page.

In most typical CMS sites there is a sidebar that contains elements like ‘Latest posts’, ‘Categories’ and a search box etc. I wanted to take it a step further and give the client full access to the sidebar and allow them to add any elements that they so wished.

A great way of doing this is by adding an area on the page where widgets can be added.

Firstly, you need to register the new widget area by adding the following code to your functions.php file:

register_sidebar( array(
		'name' => __( 'area-name', 'twentyeleven' ),
		'id' => 'sidebar-6',
		'description' => __( 'Your Area Name' ),
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget' => "</aside>",
		'before_title' => '',
		'after_title' => '',
	) );

In the ‘name’ brackets you will need to add a unique name which should be lowercase, you will also need to add a description. What you use as your description will be the name of the Widget area within WordPress. From the WordPress admin area you can drag across the widgets that you wish to have into your new widget area. You also need to make sure that the ‘id’ is a unique number and not already in use.

You then need to create the DIV on your page for the widget area to display in. To then call the widget area on your page use the following code:

if ( ! dynamic_sidebar( 'Construction' ) ) :

You can now add or remove widgets from the newly created area as you please.

How To Speed Up Your WordPress Blogs

Friday, May 25th, 2012

Does your WordPress blogs load slow? Google are taking page load speeds a bit more seriously nowadays hence it is crucial that your websites build considers the page load time. As web designers we can certainly help web developers by not designing websites with big backgrounds etc. Over 80% of the end user response time is from the front end. Images, Flash, jQuery, Javascript, CSS all play a part in how quick your WordPress or web page loads.

There are a few things that you can implement to speed up your WordPress or web page:

1. Install less WordPress plugins, do not overload it. A good plugin to have is WP Super Cache and you can download it from here. Also delete inactive plugins from the server and this would get rid of external stylesheets or javascript files that the plugin may call on a particular page.

2. Combine all the CSS together in one file and keep in header and try combing javascript together or minify using a online javascript packer which can be found here and place in the footer.

3. Use a light weight theme and makes sure you use CSS sprites and not big background images etc. If you do use lots of images you can use a WordPress plugin which will reduce the file size of a image without affect the quality of the image. This plugin can be found here.

4. Try using free content delivery networks such as Cloudflare it is quick and easy to setup and will protect your website from Malware and other nasty attacks.

5. Add the below code to your theme’s functions.php place it at the top to remove unwanted stuff from your header file.

remove_action( ‘wp_head’, ‘feed_links_extra’, 3 ); 
remove_action( ‘wp_head’, ‘feed_links’, 2 );
remove_action( ‘wp_head’, ‘rsd_link’); 
remove_action( ‘wp_head’, ‘wlwmanifest_link’); 
remove_action( ‘wp_head’, ‘index_rel_link’);
remove_action( ‘wp_head’, ‘parent_post_rel_link_wp_head’, 10, 0); 
remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0); 
remove_action( ‘wp_head’, ‘wp_generator’);
remove_action( ‘wp_head’, ‘wp_shortlink_wp_head’, 10, 0 );
remove_action( ‘wp_head’, ‘start_post_rel_link’);

If you want a web design / website design team to help you with your wordpress website then please contact us on Bristol: 01179 000 482 or Cardiff: 02920 290 080 today.

Contact Us Today...

If you have any questions about our services or want to arrange a free no obligation consultation contact us today or call 02920 290 080 for Cardiff and 01179 000 482 for Bristol.

Bit Torrent Study Discovers Most File Sharers Are Now Monitored

Ever heard of torrents or used Bit Torrent to download movies, music or shared files over the internet? Researchers have discovered that anyone who does use Bit Torrent to download files over the World Wide Web will most probably be monitored. Studies were carried out by Birmingham University and they have discovered that if someone […]
» more

Cardiff: 02920 290 080 Bristol: 01179 000 482