Archive for the ‘Themes’ category

Turn off theme CSS for the visual editor in WordPress 3.3+

January 5th, 2012

It’s been on the cards for months and WordPress has finally added the inbuilt function whereby CSS files declared on the front end are now also declared on the edit item (post/page/custom post type) pages within the admin system. This is wonderful for some but, as someone who looks at a fair few sites using a range of free, premium and bespoke themes, actually it’s a curse in disguise. Let me explain…

Let’s say you go to the WordPress theme repository and grab a nice free theme which has been written by a developer less than ‘au fait’ with WordPress functionality or best practice. You turn on the theme, all looks good and then go to write a post only to be presented with the page from hell because loose CSS rules used in style.css have broken the editor page look and feel all together. As there is no way in CSS to set a priority without rewriting the code itself you are left with a mess.

Pre WordPress 3.3 this wasn’t an issue as you needed to explicitly declare an editor style sheet in order to use the styles and make it look somewhat closer to that which you might find on the front end of the site.

Now.. turning it off! Well it will require some coding and in actual fact the simplest way to do anything about it is to make your stylesheet invisible to WordPress. Let me explain: The correct way to enqueue any CSS and JS on your site is to do something like the following:

add_action('wp_print_styles', 'theme_add_stylesheet');
function theme_add_stylesheet() {
    wp_register_style('theme_stylesheet', get_stylesheet_directory_uri() . '/style.css');
    wp_enqueue_style( 'theme_stylesheet');
}

This means that when the wp_head action is triggered from header.php in your theme the style will be printed to screen along with the other styles and scripts. The enqueue style function adds the name and location of the script to a global array which can be reused at any time. In short, WordPress knows that it is a CSS file declared by a plugin or theme and therefore can reuse it at will.

The fix is simple.. don’t use that method and, instead, use the original crude method of adding a stylesheet which is to write the HTML yourself as follows:

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />

This code, when placed in header.php of your theme, simply outputs the line in the head section of your page and includes the stylesheet unbeknown to WordPress and therefore won’t be used in the editor.

99% of the themes I have seen and used use the latter method so it’s not an issue but hopefully this will hel someone who has just upgraded and has some sort of multicoloured and wierdly laid out admin post page.

Getting the WordPress Excerpt outside of The Loop

November 16th, 2011

I have been working my way around this one for a few months now, never bothering to think about the best solution. There is not, in fact, a WordPress simple function to get the excerpt outside of the WordPress loop. Why would you want to do that you ask…

Example:

I have a plugin I have written to create a basic shopping cart and shop front. It makes use of a simple shortcode on a Page to generate the shop which is based on a custom post type called Products. The Loop is used on the main page itself to generate the WordPress Page and subsequently process the shortcode. I loop through the products using a query_posts statement to bung the data into an array (for caching and manipulating so using a child Loop isn’t possible here) and then loop over it again later on. I want to show the Excerpt (which may or may not exist) on the shop front and the full description for my individual product pages.

So I initially thought of doing something like the following:

<?php
$product = get_page($product_id);
echo $product->post_excerpt;
?>

What this approach does wrong is returns nothing at all when the user hasn’t filled in an Excerpt for the product they entered. WordPress normally takes a selection of text from the main content, strips out any HTML and shortcodes and shows that instead.

Next option is this:

<?php
echo get_the_excerpt();
?>

What this does is prints the excerpt for the page which the shop front it hosted on (the parent page) because, as far as The Loop is concerned, the context of the page isn’t a shop front, it’s just a normal Page.

So why does this not work?

<?php
echo get_the_excerpt($product_id);
?>

Well some bright spark on a blog out in the ether thought it did however, regardless of what the argument for the function was initially, it no longer works as has been depracated (the argument that is).

So what’s the solution… well sadly it’s a custom function of your own. Luckily for you I have backtraced the code and writted my own little version of the above and it works a treat…

<?php
        function get_the_excerpt($id=false) {
            global $post;

            $old_post = $post;
            if ($id != $post->ID) {
                $post = get_page($id);
            }

            if (!$excerpt = trim($post->post_excerpt)) {
                $excerpt = $post->post_content;
                $excerpt = strip_shortcodes( $excerpt );
                $excerpt = apply_filters('the_content', $excerpt);
                $excerpt = str_replace(']]>', ']]&gt;', $excerpt);
                $excerpt = strip_tags($excerpt);
                $excerpt_length = apply_filters('excerpt_length', 55);
                $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');

                $words = preg_split("/[\n\r\t ]+/", $excerpt, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
                if ( count($words) > $excerpt_length ) {
                    array_pop($words);
                    $excerpt = implode(' ', $words);
                    $excerpt = $excerpt . $excerpt_more;
                } else {
                    $excerpt = implode(' ', $words);
                }
            }

            $post = $old_post;

            return $excerpt;
        }
?>

I have put mine in a class I used for my plugins these days as a helper function however just rename it (to avoid a naming conflict with it’s namesake) and call it from your plugin or theme as you would normally.

hope this helps someone out. Please let me know if anyone knows a better or simpler way. This works for me but I really wish there wasn’t such a monumental oversight by the WordPress guys on this one (other than creating sub loops which just feels wrong and inflexible to me)

Simple custom post type features for WordPress

July 15th, 2011

I have been using custom post types in WordPress for a long time now…. In fact each new theme or plugin I write I tend to integrate a custom post type and some supplementary meta boxes here and there. If you have no idea what i’m talking about then this article probably isn’t for you… however read on and I shall explain briefly.

Custom post types are wonderful for parts of sites that don’t generally fit into the standard Post or Page model. For instance WP Ecommerce (the most popular WP shopping cart) has just started using custom post types for storing their products… you will get the idea, products being a custom post type. If I say that they are a way of storing things in WordPress that can, if needed, provide a way of administering these objects as if they were a page like any other.

Adding them yourself requires some code and adding the fields that will appear on the page will require some more. This isn’t what I want to go over right now as there is an easier way. To get an idea of what I mean, see the following screenshots…

Note the bottom three, they are custom post types

This admin interface is generated for you with 0 effort.

“Products” is generated by WP Ecommerce and my theme added “FAQs” and “Photography”. The second screenshot shows the admin interface, similar to the post/page editor, which is generated and the meta boxes which can be added very easily indeed to make it appear that way. The way that these can be added without writing any code would be to use one of the ‘More’ plugins…. These are More Fields, More Types and More Taxonomies… all freely available WordPress plugins although I tend not to use them these days (I write them into my themes instead). Take a look though.

This article was really to outline what you do with the data within these types in the real world. Of course storing the data is easy, using it requires some imagination really. The post type items are stored in the wp_posts table and the fields you add as meta data are stored in wp_usermeta. You can easily retrieve the information using standard WordPress functions.

The following function can be used to get all of the photography items and store them in an Array of Objects for looping and output any way you see fit…

function get_custom_post_type_items($custom_post_type) {
	$args = array(
	'post_type' => $custom_post_type,
	'post_status' => 'publish',
	'posts_per_page' =>-1,
	'orderby' => 'post_date',
	'order' => 'DESC'
	);

	$posts = new WP_Query($args);
	$return = array();

	if ($posts->have_posts()) {
		while ($posts->have_posts()) {
			$posts->the_post();

			$post_id = get_the_ID();

			$sub_post = new stdClass();
			$sub_post->post_id = $post_id;
			$sub_post->title = get_the_title();
			$sub_post->permalink = get_permalink($post_id);
			$sub_post->content = wpautop(get_the_content());
			$sub_post->meta_data = get_post_meta($post_id, 'meta_data_name, true);

			$return[] = $sub_post;
		}
	}

	wp_reset_query();

	return $return;
}

You can use this function in your functions.php file in your theme to be called by a page template or a shortcode if you add one to return the items you have added as custom post types. I have added a single meta data item called meta_data in each row which gets a custom field from the custom post type item called meta_data_name. In my Photography example I would just have more lines like this to get the various items from my custom meta box

$sub_post->png_image = get_post_meta($post_id, 'png_image_url, true);

Another good example use of this function would be for a featured items slider that you often see at the top of websites. One or more pages might have a portfolio item slider or a rotating banner or something. In that case you would call my function from your header.php file then loop through it outputting the appropriate HTML per line before using something like a jQuery call to construct the slider.

When you understand the applications for custom post types you might be finding yourself using them in more and more creative ways. I wrote a custom meta box a while back to link custom post type items to each other across different types. This was to allow staff member types to be linked to team and office types and so on. Then using this association you can output something like a dynamic organisational chart using a shortcode or a custom page template without having to hard code a thing.

This is a thinker, I imagine, for some people. Get in touch with me if you want any help putting these custom post types in place and utilising them on your site.

Want a website? Basic details on cost and what you are likely to be asked for…

July 14th, 2011

A lot of my clients seem to think, at least initially, that having a website built is a case of asking someone like me to write one and then their involvement stops. That is not the case as you are about to find out. This isn’t a rant or attack on people who don’t know the specifics of the web but hopefully will serve as a guide to those people or give other people like me a checklist to refine and give their clients…

First things first… Costs.

It doesn’t cost the earth to have a website written. A normal company is likely to want a presence on the net and that’s it. No need for huge fancy sites to be optimised to within an inch of their life and no need to even have a graphic designer involved. Of course you can do, and generally end up with a better site but if you want to keep things simple then it’s not necessary.

There are only really two ongoing costs for a website… domain name(s) and website hosting.

Domain Names

A domain name is very cheap indeed although costs do vary. In the past I have used a few registraars and people always have their favourites. I use Europe Registry for this site but have just registered www.letsboat.co.uk with 123-reg (aff link) for a grand total of £7 for two years.

Web Hosting

Many website developers such as myself will offer to host the site for you at £X per year. This is a good idea if you want a lot of support but ultimately it’s cheaper to do it yourself and pay a developer when (if) things go wrong. This site is hosted with imountain however I wouldn’t recommend them at all. It costs me $10 per month but I find it very slow here in the UK. I tend to recommend Hostgator (aff link) to my clients. All you need for your own website is their most basic package although I would recommend their Baby plan in case you want to host more than one site using the same account. you can pay monthly with most hosts although you only usually get the quoted prices if you pay for two or three years up front. Depending on your financial situation this might be worth doing. If you go to hostgator.com and use tortoise25 as the coupon code you will get 25% off the quoted price if it helps.

Website Development

No one, if they can help it, writes sites in pure code any more. They are a nightmare to maintain and generally not very good. Also, as the client, you end up paying for a developer to make the smallest change. This is where WordPress comes in. WordPress, a content management system (CMS), allows you and developers to write sites (like this one in fact) quite quickly and with a massive range of free themes and plugins to make sites do whatever you want them to. Galleries, shops, video players, etc… All doable without much more than a few simple steps.

Installing WordPress requires you to get a PHP enabled server, set up a MySQL database, FTP up the WordPress files found at WordPress.org, apply the theme, add some plugins and write the content in. Sounds like a lot but when you do it for a living it doesn’t take long to get something up there. However it’s kind of like car maintenance.. you think you can service it yourself and you know that, in principle, replacing a few engine consumables is an easy job and takes a mechanic only a couple of hours. Then you start the job and it takes two days and never does run right after that. See the parallel there? :)

That’s it…. you never have to pay for content updates and you can always contact me for advice/help. If you hadn’t noticed, I’m a bit of a WordPress enthusiast. But then why not when WordPress is used for a huge number of sites on the internet (50,000,000 I think was the last count I read).

What do you need to provide to a Website Developer?

Simple enough question to ask, hard question to answer really. Here is a very basic list…

  • Content
  • Look and feel
  • Gather resources to use

And then for any site with an ecommerce aspect:

  • Products
  • Payment processor (Paypal, Clickbank, Sagepay, etc…)
  • Gather resources for download or delivery

Let me expand on these…

Content is self explanatory. I recommend firstly thinking about how many pages you want on the site and then jotting down, in something like Word, the content for each page. Images to compliment text is always a nice addition but can be done later. Additionally with a domain and a site you might want to let people get in touch with you. Have a think about what phone numbers (if any) and email addresses you want public or if you just want a contact form.

Look and feel is something that will definitely need to be expanded on. If you have a look at a few themes around the internet. There are literally thousands of them out there, loads free and others premium. Either is ok and neither better than the other. WordPress has it’s own showcase of free themes (required to be free to be in the list!). Someone like myself will firstly ask if you want a graphic designer involved, at which stage this process will be escalated to another level of cost and complexity. However, if you want something basic then a free theme will do. There are a large number of ‘framework’ based themes for free out there which allow people to edit their theme without touching the code. They tend to be very basic but might be a good starter. Otherwise there are even more standard themes about which can be modified to suit if need be. I normally recommend that people give up to three themes from the directory they like and then a new theme can be made which incorporates the better features of each.

Gathering resources is really just a cursory note for you to gather any images or logos (your company logo for example) in digital form to be added to the site. They need to be as high a quality as you can find. Images like logos should really be in JPG, PNG or GIF format and be bigger than needed so they can be trimmed to fit for the site. You can make images smaller and retain quality but not make them bigger.

Ecommerce aspects really are similar… Products is just something, as before, for you to think about. The descriptions for the products, the pricing, images and ways of getting hold of them (postage, pdf, etc..)

Payment processor is what we call the way in which people are asked to pay for their items. Normally Paypal is the standard for small sites. People tend to have accounts via eBay these days anyway. Other types of processor are available but tend to incur monthly costs (£20/month I think for Sagepay). Paypal is the easiest if you want to keep ongoing costs down. The requirement to sell is that you have a premier or business account. To do it you just need to login and look at your account settings then jump the hoops to update your account. This simply involves linking a bank account to you Paypal account (takes a few days, best done in advance of being needed). Nothing official otherwise needed.

Gathering resources is, again, just putting together the images and the content for the products. There are several shopping carts for use for downloads and ecommerce within WordPress.

SEO

Perhaps the buzzword of the net these days. I’ve not yet met someone that hasn’t heard the acronym although often people don’t know what it means… only that they want it. Plugins exist for free for WordPress to allow you to add your site to Google and other search engines and to allow you to compliment your content with the right sort of data to get you noticed. There are quite a few guides on the internet to help you through this.

Summary

So what was the point of all that then? Well… hopefully now you shall know about the sorts of things you are likely to be asked for when wanting a website and will be prepared for your initial conversation with website developers if that’s the direction you want to go.

By all means get in touch with me to go over any project you have in mind or even just to get an idea of how much it would cost for me to do it all for you. Take a look at some of the sites I have done in the past on my Portfolio page or get in touch using either of my contact or get a quote forms.

How to convert your site to WordPress

March 16th, 2010

Wordpress LogoI recently had a conversation with someone who had decided to come to WordPress to take advantage of a plugin or two and wanted to know how to get an existing site into the correct theme structure as required. It took a lengthy email or two to explain but it struck me that lots of people must be asking the same questions over and over. So in this post i shall try to explain how to get a theme together, or rather where to start

So… first, a bit of logic

Logically speaking a standard layout web page can be split into four distinct areas as follows:

  • Header
  • Footer
  • Sidebar(s)
  • Content

And as such WordPress uses different theme files to render the appropriate sections. We need to split our HTML page into those different files. There are, however, lines of code that WordPress needs you to put into each of these files and so tbe best way todo this without missing anything is to recycle another theme. So… go to your WordPress install and visit /wp-content/themes/ and…

  1. Duplicate the directory called ‘default
  2. Open style.css in a text editor and edit the name of the theme and any other information you feel like
  3. Either remove or replace screenshot.jpg from the theme directory so it looks different in the theme menu

That’s it, you now have a skeleton to work from and it’s time to make it look like your site. Let’s assume you have a simple brochureware site and, therefore, don’t need any blog type pages. Largely these sites have a standard consistent layout on each page (often except the home page but that difference is for another tutorial) and WordPress uses this consistency to slot in the appropriate information for each page. We do this by…

  1. Choose a short yet typical page from your site and view the HTML source
  2. Open 4 separate text files from the new theme directory in your favourite text editor. They are: header.php, footer.php, sidebar.php and page.php
  3. From the HTML source take the top section of code (usually as far as the content and sidebar code inclusive of a menu assuming you are using a top horizontal bar navigation) and place it into header.php making sure to preserve the obvious dynamic sections of code (anything between <?php and ?> can be assumed to be dynamic)
  4. Do the same with the footer into footer.php (the section below the content and sidebar that often contains SEO links and copyright notices)
  5. The remaining block should contain the content and sidebar code… simply cut out the sidebar code into sidebar.php
  6. Finally split the content code into the bit before the text and the bit after the text (ie: layout code stripping out the text itself). Then paste these sections around the ‘while’ loop within page.php.
  7. (optional) copy your stylesheet into style.css making sure to preserve the comment at the top of the file as this is used by WordPress to define the theme and without which will not pick up any of the code.

Step 6 will likely be the most difficult to do as there are three or four important lines of PHP code in there. Firstly the line that reads <?php get_header(); ?> is the code that calls header.php. Likewise <?php get_footer(); ?> and <?php get_sidebar(); ?> call their appropriate namesakes. Make sure that they are in the correct logical positions for the page to render in the right order.

The Loop

The hardest section is what is called ‘the loop’ by WordPress bods. This is the section of code that shows the post(s) from the database relative to the page you are looking at. The Loop often falls into the following form:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
 <div id="post-<?php the_ID(); ?>">
 <h2><?php the_title(); ?></h2>
 <div>
 <?php the_content('<p>Read the rest of this page &raquo;</p>'); ?>

 <?php wp_link_pages(array('before' => '<p><strong>Pages:</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?>

 </div>
 </div>
 <?php endwhile; endif; ?>

You shouldn’t really need to change any of the code itself but you might need to edit the encapsulating HTML to make your styles fit in. For example if your page titles are not in H2 tags then you need to change it to suit etc etc…

Testing it!

This will always be a case of trial and error until you know what you are doing so don’t worry if it all goes pear shaped. That’s what the undo button is for!

To test that your theme is working properly then you need to visit your sites back end at /wp-admin and click the link on the left hand side called ‘appearance‘. The themes page will appear and to activate your theme you simply find it in the list and click ‘activate’. Then view the front end of the site and see what it looks like.

At this stage you might be confused because the home page looks different to the rest of the site. This is because, by default, WordPress uses the index.php file from your theme directory to generate the home page. To change this visit the settings -> reading page from the left menu and use the dropdown box to choose an appropriate page to be used for the home page.

What’s next?

Ok so your theme looks like it did before you spent hours making the them for the WordPress site… why on earth are we using WordPress at all you ask! Well if you were to create a new page for your old site then you would have to duplicate an HTML file, trawl through code (or look at Dreamweaver or another WYSIWYG) to find the sections to replace before uploading to your site and updating the links in the various menus as appropriate. With WordPress you just add a ‘page‘ using the nice admin system and it’s all done for you.

I always tell my clients to go and have a look at the WordPress plugins directory for ideas and things to ad to their site. A word of warning though, some plugins conflict with others and too many plugins might slow your site down considerably. Over time you will get used to a core few you know and trust.

Feel free to ask me any questions about WordPress, PHP or other and hopefully I will be able to help you decide what’s the best direction for your site to take. Expect a lecture about how good WordPress is though!