Posts Tagged ‘Wordpress’
A Hidden Cache
8/9/2010 9:00 AM By Jeff BThis last post on WordPress is going to be on caching. WordPress, by its very nature, is dynamically generated using PHP. While this allows us to do very cool stuff, it can also take a heavy toll on a server. It’s not uncommon for a blogger to write a very popular post and end up getting Dugg or Fireballed, which can crush even the mightiest of servers.
So how do you avoid that as a blog developer? Use caching. WordPress has some built-in caching mechanisms, which we definitely want to enable by adding this to your wp-config.php file:
// Enable the WordPress Object Cache:
define(ENABLE_CACHE, true);
For a simple blog, that might be enough. But you’ve kitted yours out with all manner of brilliant plugins, and each one adds more load to the site. So we need some more caching juice than the built-in system can provide. This is where W3 Total Cache comes in.
This bad rider can cache pages as static HTML, minify your CSS and JavaScript, cache database queries, and hook your site into a CDN for some serious speed gains. That last one is really only needed if you’re running a huge site (think Mashable or Smashing Magazine, both of which use W3TC).
But as with many powerful tools, it has a learning curve and requires some setup. After you install it to your site (and if you’re using WordPress 3.0, you’ll want to grab the developer version until version 0.9 is officially released) but before you activate it, you’ll want to set the wp-content folder to be writeable by WordPress, if it isn’t already. Then go ahead and activate the plugin. It will generate some new files in the wp-content folder and create a new folder to house the cache.
Now we want to head over to the settings area for W3TC and configure it. By default, it will cache everything to disk, saving things as static HTML, CSS, and JS files. If you’re on a server that has APC, XCache, eAccelerator, or memcached installed, you set W3TC to use whichever opcode you have installed instead of writing to the disk, resulting in potentially greater speed gains.
You’ll want to go through each of the settings areas, but the place that really can confuse is the minify section. Here, under the JavaScript and CSS portions, you want to copy in the URL of every script and CSS file your site is loading and set whether you want them to load in the header or footer, using either normal or non-blocking (asynchronous) style load. W3TC will scour your pages, find these URLs, and combine these files all into a single, minified file, once for JS and once for CSS. If you’re loading a bunch of JavaScript, this can significantly decrease load time and bandwidth, as only a single lookup and file transfer will occur for every script on your site.
You can even set it to have certain scripts only load on particular templates, which is pretty handy.
Once this is all done, you’ll want to log out to test that the cache is working well, as it won’t be caching anything for admins by default.
You can use the YSlow extension for Firefox to test your site’s capabilities, and see how it stacks up optimization-wise.
Setting up W3TC should help to stave off any issues of bandwidth and speed, resulting in a much more pleasant experience all around.
Query Me This, Batman!
8/6/2010 9:30 AM By Jeff BOccasionally, when listing posts in WordPress, you may want to display things differently or only load certain posts. This is done by modifying, or completely replacing, the query. There are two ways to do this, depending on the result you want for your online blog. One is to modify or replace the global $query_string variable for the entire page using the query_posts() function; the other is to create a new query using the WP_Query() function. Both take the same arguments, either as an array or in what’s called a “query-style” string.
Let’s try a simple modification of the query using query_posts():
<?php
// display posts organized by title in ascending order
$posts = query_posts( $query_string . '&orderby=title&order=asc' );
if( $posts ) : ?>
<div class="post">
<h1>Ordered by Post Title (Ascending)</h1>
<?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<p><?php the_content(); ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
As the comments say, we’re reordering the posts by title. So how does this all go down? Well, we create a new variable called $posts and set it to the result of our query_posts() function. Since we want to preserve the posts we’ve already found with the original query, we include that by putting in $query_string, which holds the query generated by asking for the page, Then we add two more parameters in query-style string: orderby=title and order=asc. Each argument in a query-style string must start with an ampersand if it’s preceded by another argument.
If we didn’t include $query_string, we would discard whatever result the initial query brought us and load every post, sorted alphabetically, as we would only be specifying order. So why would we ever need to use WP_Query()?
Well, what if we want multiple loops? The $query_string variable is global, so if we modify it at one point, then loop through its results, we will continue to work with the remainder if we attempt to display any post information later. Not only that, but there’s the potential to interfere with plugins which make use of the Loop, invalidate WordPress conditional tags, and you have to deal with resetting, rewinding, offsetting, and other messiness.
It is far simpler to craft our own custom loop, like so:
<h3>Recent Articles</h3>
<ul>
<?php
$recentPosts = new WP_Query();
$recentPosts->query('showposts=5');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
This is a vey simple query, which just asks for the five most recent posts. As with any Loop, you are free to use any of the standard post tags (e.g. the_title(), the_permalink(), etc.)
As for what arguments you can use in a query, you can ask for specific categories/tags; require that a post is in a specific category or tag; include or exclude a post or posts based on their ID, category, tag, name, or slug; set the number of posts per page (when using pagination); find posts in a specific time period; or even only show pages that match certain custom fields. This last bit can be very powerful.
Armed with this knowledge, you can really add to your theme by using custom queries and do some pretty spiffy stuff!
Going Loopy!
8/6/2010 9:00 AM By Jeff BWe’re going to dive into the heart of WordPress with this post: The Loop. That, of course, begs an explanation of what the Loop is. The Loop is used by WordPress to display the results of the current query; generally speaking, this is a list of current posts from newest to oldest. The Loop does exactly that, looping through and applying a set of HTML to each post as it lists them.
If you open the index.php file for the default theme in WordPress, Twenty Ten, you eventually come to a line of code that reads:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
This is the beginning of the Loop. The Loop then continues, ending with something like this:
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
So, for each post found by the loop, it generates whatever HTML you have been the_post() and endwhile;. This might be something like this:
<?php // Start the Loop.
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php // Display the Title as a link to the Post's permalink. ?>
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<?php // Display the date (November 16th, 2009 format) and a link to other posts by this posts author. ?>
<small><?php the_time('F jS, Y') ?> by <?php the_author_posts_link() ?></small>
<?php // Display the Post's Content in a div box. ?>
<div class="entry">
<?php the_content(); ?>
</div>
<?php // Display a comma separated list of the Post's Categories. ?>
<p class="postmetadata">Posted in <?php the_category(', '); ?></p>
</div><!-- end .post -->
<?php // Stop The Loop (but note the "else:" - see next line).
endwhile; else:
// The very first "if" tested to see if there were any Posts to display. This "else" part tells what do if there weren't any. ?>
<p>Sorry, no posts matched your criteria.</p>
<?php
// REALLY stop The Loop.
endif; ?>
So, for each post, a <div> with a unique id based on the post’s WordPress ID number and a general class from the post_class() function is created. Within it, the title of the post, which is also a permalink to the post’s single page, is displayed, followed by the date of the post’s publication and the author. Finally, another <div> is created to contain the actual post content, which is output by the the_content() function, and then the .post <div> is closed.
If, for some reason, no posts are returned by the Loop, the else portion of the Loop runs instead, which outputs an explanation that no posts were found. Many theme authors will write something humorous here. This, however, is different from your 404 template, which will be shown if the URL doesn’t lead to an actual page.
Many times, a function of WordPress cannot live outside the Loop, as it depends on some information loaded from the the_post() function, which generates a variable called $post that is an array of all post data that was summoned using the current query.
Utilizing conditionals and if statements, one can really juice up the Loop and have it do some spiffy stuff. We’ll get into some of that next time!
Filtering WordPress’ RSS feeds
8/4/2010 9:30 AM By Jeff BThis next one is a pretty nifty trick: adding custom content to your RSS feed. Since WordPress is very actively developed and upgraded often, it’s generally a very bad idea to make any changes to the core files, which is what’s needed if you want to directly change the RSS feed template. Thankfully, the folks at Automattic gave us some tools within WordPress to avoid having to hack the core, with the filter system.
So what happens? Certain functions can be hooked into, have further changes made, and then output once again using a filter. It looks something like this:
function contentModifier ($contentToFilter) {
// do stuff with content
return $contentToFilter;
}
add_filter('filterName', 'contentModifier ');
There are a ton of filters built in to WordPress, and many plugin authors offer their own filtering as well. In the case of this particular goal, we need to use the the_excerpt_rss and the_content_rss filters. To do that, we’d write something like this into our functions.php file in our theme:
function your_rssContent($content) {
$content = $content . '<p>Like this post? Why don't you <a href="http://twitter.com/">follow me on Twitter</a></p>';
return $content;
}
add_filter('the_excerpt_rss', 'your_rssContent');
add_filter('the_content_rss', 'your_rssContent');
This would add a link to Twitter at the bottom of every item in the RSS feed. Lots of different things can be done here, such as adding a thumbnail, listing related posts, or really, just about anything.
Okay, but on One Condition…
8/4/2010 9:00 AM By Jeff BNow that we’ve covered what a theme is and how they work, let’s dive into some of WordPress’s conditional tags. You’re welcome to head over to that more in-depth article at the codex, but we’ll go over some of the basics here.
Each of these conditional “tags” is actually a PHP function, which in most cases takes an ID, string, or an array as a parameter. Of the many that exist, here are a few of the most useful ones:
is_front_page()– A condition for whenever the front-most page of your site is being displayed.is_home()– If you’ve left WordPress in its default state, this corresponds to the home page of your site. If you’ve set a page to be the “Front page” (in Settings > Reading), this condition will correspond to your “Posts page”. A confusing name, to be sure; best to think of it as “is_blog” instead.is_single()– This is for any single Post, attachment, or custom Post Type page being displayed; it triggers false for Pages. If you supply it with an ID, title, slug, or array of any of those (either one time or intermingled), it will only trigger true with the string. E.g.:<?php if (is_single('17') { … } ?>is_page()– Returns true when any Page is being displayed. Likeis_single(), it can be fed an ID, title, slug, or array of any of those. E.g.:<?php if (is_page(array(42,'about-me','About Me And Joe'))) { … } ?>is_page_template()– Returns true if a page template is being used. If you give it a specific template’s filename as a string, it will only return true if that particular template is in use. Useful for modifying whatheader.php,sidebar.php,footer.php, or any other included file does, since the template file itself will already be loaded, and this function isn’t needed in the file itself.is_category(),is_tag(),is_tax(),is_date(),is_archive– These all correspond to particular types of archive pages, with the last being a generic condition for any archive page. The first three can accept an ID, name, or slug to limit the scope of their condition.in_category()andhas_tag()– These two require a string be supplied in order to operate correctly, and while both accept an ID, onlyhas_tag()accepts a slug as well.
The idea with these conditionals is to use them to control what is displayed on a particular template. For example, if you happen to be crafting a simpler theme with only the index.php template file, these can be used to do certain things based on the page WordPress is displaying. If you want the category to only appear when a single post is being viewed, you could do something like this:
<?php if (is_single()) echo 'This post is in the ' . single_cat_title() . ' category.' ?>
What’s likely the most common usage is to take advantage of the is_page() conditional to perform a task only on specific pages, such as loading a different sidebar on a per-page basis or including some secondary content that should only show up on a specific page. Something like this:
<?php
if (is_page(array(42,'about-me','About Me And Joe'))) {
get_sidebar('about');
}
else {
get_sidebar();
}
?>
The whole idea here is to take greater advantage of PHP’s scripting abilities and not write the same thing over and over again, as you would have to do if you crafted separate blog templates for each page. Armed with this knowledge, you can begin to see that the possibilities for how your WordPress site works are limited only by your imagination!
Theme development basics, or why WordPress rocks
8/2/2010 9:30 AM By Jeff BAll right, let’s talk theming. WordPress has a great wiki called the Codex that talks about everything WordPress, and there’s a marvelous article over there that goes in depth regarding themes, but here’s a quick rundown, and you can head over to the Codex if you want to dive deeper.
WordPress’ themes appear to function as a mere skin for your site, but they can go far beyond merely changing the look of things and actually provide additional presentation abilities. Physically speaking, a theme is a collection of template files. The most basic theme looks like this:
index.phpstyle.css
WordPress will use the stylesheet, which is always named style.css to identify the theme (you’ll want to place some specially formatted comments in your style.css to do this identifying). Then it will find the index.php file, and that’s that. However, this sort of theme wouldn’t offer very much in the way of functionality.
A more common approach would be to break things apart quite a bit more and utilize WordPress’ query-based logic to load specific templates for specific types of pages. That would look like this:
404.phparchive.phpfooter.phpfunctions.phpheader.phpindex.phppage.phpsearch.phpsidebar.phpsingle.phpstyle.css
Now we’ve got some more control! So what’s happening here? Well, whenever WordPress loads a page, it runs a query to determine what sort of page it is. If that query matches one of the specific page templates, it will use that one; otherwise, it falls back on the index.php template, which is always used for the basic posts list. An explanation could take many words, but thankfully, the good folks at Automattic have written a Codex article on Template Hierarchy and made us this lovely diagram:
If you’d like to read some more on developing your own themes, take a look at the Theme Development article over at the WordPress Codex.
Plug it in, plug it in!
8/2/2010 9:00 AM By Jeff BNow, one of the most amazing things about WordPress is how extensive it is. Owing to its free, open source nature, a very large, talented community has sprung up around WordPress, and at this point, thousands of plugins exist for the software. It used to be quite difficult to find them, but some time ago, Automattic (the makers of WordPress) set up a great directory for all of the plugins and themes created by the WordPress community and released freely. It should be noted that there are commercial plugins and themes, but these tend to be very high-powered pieces of software. By and large, most plugin and theme authors release their creations freely.
With that said, you’re welcome to peruse the WordPress Plugin Directory and the WordPress Free Themes Directory on your own, but here are some favorites this writer uses daily on his own site as well as client websites.
- Akismet: This one comes bundled with every WordPress install, and if you’re going to enable comments on your blog, is a must. It’s an anti-spam measure, and no matter how little traffic you receive, if you’ve got comments enabled, the spammers will find you. So turn it on, and follow the instructions, or disable comments entirely.
- Comment Relish: Continuing with the comments bit, this one is quite a delight. Upon commenting on another writer’s blog one day, an email materialized in this writer’s mailbox, thanking him for the comment. Upon asking how this was, the other blogger pointed out this plugin. A really great way to keep your audience engaged!
- Dunstan’s Time Since: This one is pretty nifty. It can replace all of the time and date stamps on your posts with relative timestamps. So instead of “June 30th, 2010”, it would say “Yesterday”. Quite cool!
- flickrRSS: If you’re a flickr user, this is the plugin to have. It can display any photostream, either using a widget or by inserting its PHP function into your template. You can see it in action in the left sidebar of [ berkleebassist ].
- GigPress: The ultimate plugin for the working musician. Head on over and read all about it; this one’s got way too much awesome going on to be contained in this list.
- Google Analyticator: Hopefully, you’ve already learned about Google Analytics and are eager to make sure your WordPress install has things properly included. Well, this is the plugin for you!
- Google XML Sitemaps: Going along with the previous plugin, this one ensures your blog is well-received by Google’s search engine and indexed kindly and accurately. Highly recommended.
- iMax Width: Very useful if you plan on shuffling through lots of themes, or if you are deploying WordPress for an end user with little to no HTML knowledge, this guy ensures that no matter what image is inserted into a post or page, it does not exceed a certain size. Very handy to ensure layouts don’t break!
- Lightbox Plus: There are a lot of lightbox plugins out there for WordPress, but this, after much searching, appears to be one of the best. Highly recommended.
- pageMash: Probably the easiest way to reorganize the order of your pages, set the hierarchy, and hide certain pages from the site navigation / page lists. While WordPress’s new custom menu system makes this less essential than it once was, still an excellent tool for managing your pages.
- Redirection: Brilliantly useful if you change a post’s or page’s name, as it ensures that the old URL redirects to the new one. It can also monitor 404 errors and easily allow you to craft redirection rules for these missing or incorrect URLs.
- Relevanssi: WordPress’s built-in search is very simple, but this brilliant plugin juices things up and empowers the search to be relevance-sorted, instead of chronologically or alphabetically sorted, as is the default.
- SEO Ultimate: We could spend a whole article talking about SEO Ultimate, and we will. Stay tuned.
- Simple Tags: Juices up the built-in tagging system, offering more autocomplete options, a listing of commonly used tags, and tag suggestions both from within your own tags and from external sources.
- Twitter Tools: There are a number of plugins to integrate Twitter into your WordPress install, but this is a favorite and long-time contender.
- Use Google Libraries: Absolutely a must-have to keep your install moving along quickly and lighten the load on your server, it checks all of your JavaScript for any files that could be served from Google’s CDN instead, and replaces the URL. Most useful for jQuery and the other libraries.
- W3 Total Cache: Another crucial but very complex plugin, we’ll discuss this one in a later article.
- WordPress Admin Bar: A very nifty piece of work; places a global menubar across the client side of your site whenever you’re logged in as an admin. Makes getting to the edit area for a post or page quite simple.
- WP-DBManager: The best database management and backup plugin out there, period. Get it, set it up to back up your DB, and forever feel safe from blowing things up.
- wp-Typography: This one is quite nifty, even if it sometimes causes conflicts. It can hyphenate your text (vital if you’re planning on doing justified text like this blog), create proper ordinals (like this: 1st), and wrap your ampersands, quotations, all-caps text, and numbers in spans to style them separately from other things. Check it out if you want some spiffy typography.
- WPtouch iPhone Theme: Last one on this list, you want to cater to your iPhone / iPod Touch viewers, and this is one of the best ways to do it, short of crafting your own mobile template. They’ve got a paid pro version that was just released, some very cool upgrades to the free version.
Quite a list, I know, and there are plenty of other plugins that could have been included, but we’ll leave off there for now.
The famous five minute install
7/30/2010 9:30 AM By Jeff BNow, we’ll assume you’ve already given WordPress a spin using the hosted version at wordpress.com, but now you’re ready to dive in and really get the ball rolling with your own, self-hosted install of the software.
First up, let’s make sure you’ve got everything you need. You’ll want to ensure your hosting company (the company that houses your website) has PHP 5.0 or greater and MySQL 5.0 or greater installed. If not, they should definitely update both, as each has been out for some time now, and there’s no excuse to not be using the current, stable version of both.
Now, the steps to get installed:
- Head over to wordpress.org and download the current, stable version of WordPress (3.0 as of this writing).
- Unzip that to anywhere on your computer. It will create a folder called “wordpress”.
- Using your host’s control panel, create a new database for WordPress. Make sure to note not only its name, but also your database connection settings.
- Open the
wp-config.phpfile, and adjust the database settings to reflect the settings you noted in the previous step. Often, the host will remain “localhost”, but always, the user, database name, and password will need to be customized to suit your configuration. - Now upload WordPress to wherever you would like it to live on your server. I recommend keeping it in its own folder, unless you’re creating a new site that will be entirely built on WordPress.
- Open your browser, and go to http://www.example.com/wordpress/, replacing example.com with your domain, of course.
- Follow the on-screen installation instructions.
And that, my friends, is it. You now having a working installation of WordPress!
Yet more introductions…
7/30/2010 9:00 AM By Jeff BNow we’re going to get into a particular PHP application: WordPress. But what is WordPress, exactly?
WordPress was originally crafted as an engine for blogging—the journal-like writing that’s become so ubiquitous nowadays. As time has gone on, and the community surrounding the open source software has grown, its abilities have expanded dramatically. As of this writing, it stands at version 3.0 and has grown into a quite powerful CMS. Beyond the basic blogging system of reverse chronologically ordered posts, it offers hierarchical pages, categorizing and tagging of posts, automatically-generated archives of posts based on date, tag, category, and author, custom post and page types, built-in media upload, insertion, and management, and a host of other features. And it’s quite endlessly expandable via plugins.
WordPress comes in two flavors: the original, self-hosted version you download from wordpress.org and their free, hosted version at wordpress.com.
As for some examples, you could take a look at this writer’s site, [ berkleebassist ], or at the site of Halftone Productions, and of course, you’re reading this from within a WordPress blog, as Artisan runs its blog on the WordPress engine.
As you can see even from just those three sites, you can do some very different things with WordPress. If you want to get started with WordPress before diving in with your own self-hosted version, you should go ahead and create an account at wordpress.com, and get a feel for the basic version of the software.








Subscribe by RSS