WordPress Guy

Easily Updating WordPress with Subversion

Lately I was having a lot of trouble updating the WordPress installs on all the blogs that I manage. Doing it with FTP can be extremely slow and time consuming. I used to upload the zipped WordPress directory and then unzipping and updating via SSH, however, this still was pretty complicated. I’ve been wanting to try updating WordPress via Subversion for ages, and I finally did.

There is an article about this on the WordPress site, but I’m going to outline what worked for me.

Connecting to your host via SSH

First, you need to have access to your host via SSH. If you don’t know how to do this, ask your hosting provider.

Installing Subversion

My MediaTemple DV server didn’t have Subversion installed, that’s one of the reasons I didn’t use it. So first, I had to install it. After a couple of hours of reading tutorials, installing packages and beating my head against the wall, I found out that you can get Subversion and other stuff by installing something they call “Developer Tools” from the admin panel.

Again, if you don’t have Subversion installed on your server, the best option is to ask your host.

Seting up a Subversion repository

For the sake of this tutorial let’s assume that your current WordPress install is at root level (”/WordPress”).

Here comes the fun part… Once you’re connected to your host via SSH you’ll have to create a temporary directory where we’re going to setup our repository (this varies depending on your setup):

cd /
mkdir wp
cd wp

Now download the latest WordPress version (currently 2.5.1):

svn co http://svn.automattic.com/wordpress/tags/2.5.1/ .

To avoid problems later, I’m removing everything from the wp-content directory:

rm -rf wp-content/themes
rm -rf wp-content/plugins
rm -f wp-content/index.php

Then we’re going to copy the custom stuff from our current WordPress, that is, the themes, the plugins, the uploads, etc.

cp -rpf /WordPress/wp-content/* wp-content
cp -p /WordPress/wp-config.php .htaccess ./

Now we rename the old WordPress directory to something else and the new one to what the old one was called.

mv /WordPress /WordPress.bak
mv wp /WordPress

That’s it. Check that your blog is still working, if something went wrong you can just revert to the old version by doing the last commands the other way around:

mv /WordPress /wp
mv /WordPress.bak /WordPress

From now on, you can easily update using the following command (changing the “2.5.1″ part to the appropriate version, of course):

svn sw http://svn.automattic.com/wordpress/tags/2.5.1/

It sure is a complicated process if you don’t have much terminal / shell / ssh experience, but it’s definitely worth the effort.

An archives page with all the posts in cronological order

An archive page is nothing more than a page with links to your blog posts ordered by date, category, etc. In this tutorial we’re going to list all the blog posts in our blog, ordered by date in a hierarchical way. Something like this:

  • May 2008

    • 25 - Lorem ipsum
    • 12 - Dolor sit amet
  • April 2008

    • 22 - Adipiscing elit
    • 18 - Consectetur
    • 3 - Ipsum amet

Cool, eh! Let’s go…

The page

First create a new php file and type this at the very beginning:

<?php
/*
Template Name: Hierarchical Archives
*/
?>

This will help us identify the template when we create the archives page in the WordPress back-end.

Now, let’s enter the basic page code. You may want to open the page.php file of your theme, and copy the structure. I’ll be using the default “kubrick” theme structure for this tutorial:

<?php get_header(); ?>
 
<div id="content" class="widecolumn">
 
<!--Here is where our code will go-->
 
</div>
 
<?php get_footer(); ?>

The code

Ok and now this is the code that will print the actual list of posts:

<?php
 
// Declare some helper vars
$previous_year = $year = 0;
$previous_month = $month = 0;
$ul_open = false;
 
// Get the posts
$myposts = get_posts('numberposts=0&orderby=post_date&order=DESC');
 
?>
 
<?php foreach($myposts as $post) : ?>	
 
	<?php
 
	// Setup the post variables
	setup_postdata($post);
 
	$year = mysql2date('Y', $post->post_date);
	$month = mysql2date('n', $post->post_date);
	$day = mysql2date('j', $post->post_date);
 
	?>
 
	<?php if($year != $previous_year || $month != $previous_month) : ?>
 
		<?php if($ul_open == true) : ?>
		</ul>
		<?php endif; ?>
 
		<h3><?php the_time('F Y'); ?></h3>
 
		<ul class="month_archive">
 
		<?php $ul_open = true; ?>
 
	<?php endif; ?>
 
	<?php $previous_year = $year; $previous_month = $month; ?>
 
	<li><span class="the_day"><?php the_time('j'); ?></span> <span class="the_article"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></span></li>
 
<?php endforeach; ?>

How does this work? Well… it’s a little hard to explain. Basically, we’re using the get_posts() function to get all the posts (numberposts=0 means all of them), ordered by date (orderby=post_date) in descending order (order=DESC). Then, we’re looping through every last one of them, comparing it’s published month and year to the previous one and echoing the year and the month accordingly.

Wrapping up

That’s basically it. Now save this file and upload it to your template directory (/wp-content/themes/your_theme). Then create a new page in the WordPress back-end, selecting “Hierarchical Archives” in the page template drop-down menu. And you’re done.

Hope you liked the pseudo-tutorial ;-).

How to make a random post button

Ever wanted to have a “Random Post” link or button in your sidebar but you don’t know where to start? Well, today I’m going to show you how to do it.

The principles

As you may know already, WordPress posts are stored in a MySQL database. For us to obtain the URL to a random post from that database, we need to run a MySQL query. It’s pretty simple actually, thanks to WPDB, a built-in database class that comes with every WordPress install, we don’t need to bother about database names, passwords, connections and disconnections, etc. We just need to run the query and echo the result.

The MySQL query

Our database query needs to look inside the posts table and select one random post from the published posts. This is what the query looks like:

SELECT guid FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY RAND() LIMIT 1

Let me explain how exactly this MySQL query works:

  1. SELECT guid - Select just the guid column value, which is where the URL to the post is located.
  2. FROM wp_posts - From the posts table
  3. WHERE post_type = 'post' - Since attachments are also saved in the posts table, we need to specify that we just want posts
  4. AND post_status = 'publish' - We just want the published posts, not scheduled posts, not drafts
  5. ORDER BY rand() - Get them in random order
  6. LIMIT 1 - And get just one result

The PHP code

Now, let’s type the PHP code. As I said, we’re going to make it simple by using the WPDB class, which comes bundled into WordPress. This is our code:

<?php
$randomPost = $wpdb->get_var("SELECT guid FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY rand() LIMIT 1");
echo '<a href="'.$randomPost.'">Random Post</a>';
?>

In the first line of the code, we’re running the database query using the WPDB get_var() function, and storing the result inside a $randomPost variable. Then, in the second line, we’re echoing the link, pointing to the URL stored in the $randomPost variable.

Note I’m using $wpdb->posts instead of wp_posts, that way, we make sure that we’re selecting the right table, since you could have changed the table prefix (which by default is ‘wp_’).

That’s it for today. I hope you enjoyed the mini-tutorial.

How to use initial caps in your WordPress theme

Initial CapAlso called initial letters, initial caps are enlarged characters that are used as the first letter of a paragraph. Initial caps can be in a different font, different color, or you could even use images instead! In this tutorial we’re going to learn how to create initial caps using special HTML markup, CSS styling, and then we’re going to automate the process with a PHP function.

The HTML

In order to style the first letter of a paragraph differently, we need to wrap it inside a special HTML element that we can later style by adding a few lines of CSS. For this tutorial I’m going to use a simple span element, with the “initialcap” class. The resulting paragraph will look like this:

<span class="initialcap">L</span>orem ipsum dolor sit amet, ...

Remember not to repeat the letter after the span ;-)

The CSS

Here comes the tricky part, due to the fact that every theme has different font size and line height values you’ll have to adapt this part to your theme. I’m going to assume that our paragraph has a font-size of 14 pixels and a line height of 18 pixels.

1. Float! We need to make our capital letter float left in order for the paragraph text to flow around it.

span.initialcap{
    float: left;
}

2. Font size. We assign it a font size of 40 pixels (again, this may vary depending on your theme’s CSS), and a line height of 35 pixels, which is twice the line height of the paragraph minus 1 pixel (just in case).

span.initialcap{
    float: left;
 
    font-size: 40px;
    line-height: 35px; /* Double the line height minus 1 pixel */
}

3. Extra styling. We’re going to use a serif font, make it blue, and add a little bit of spacing on the right.

span.initialcap{
    float: left;
 
    font-size: 40px;
    line-height: 35px; /* Double the line height minus 1 pixel */
 
    font-family: Georgia, "Times New Roman", Times, serif;
    color: #2583ad; /* Blue */
    padding-right: 5px;
}

You’re probably going to have to play a little bit with the font size and line height values though.

Automation

Ok, so you’ve added the necessary CSS to your style.css file, but isn’t it a bit of a hassle to have to add the HTML markup every time you write a new post? Well, this bit of PHP code will do this for you:

function wpguy_initial_cap($content){
 
    // Regular Expression, matches a single letter
    // * even if it's inside a link tag.
    $searchfor = '/>(<a [^>]+>)?([^<\s])/';
 
    // The string we're replacing the letter for
    $replacewith = '>$1<span class="capital">$2</span>';
 
    // Replace it, but just once (for the very first letter of the post)
    $content = preg_replace($searchfor, $replacewith, $content, 1);
 
    // Return the result
    return $content;
}
 
// Add this function to the WordPress hook
add_filter('the_content', 'wpguy_initial_cap');

How does it work? Basically, our function takes the content of the blog post, and wraps the first letter with our special markup.

All you need to do is paste it inside the functions.php file of your theme.

I hope you enjoyed this tutorial! Remember to post your thoughts and questions in the Comments section.

How to make a tag cloud page

Have you noticed that many blogs have a tag cloud in their sidebars? however, not many have a tag cloud page. Why a tag cloud page you may ask! Well… many reasons: de-cluttering your sidebar, adding interactivity to your blog, … Or maybe you have so many tags that they don’t fit in your regular tag cloud widget.

So that’s what this tutorial is about: creating a tag cloud page.

Before we start

Before we start, you need to be running WordPress version 2.3 or later, and of course have a bunch of posts with tags, otherwise you may end up with an empty tag cloud.

Creating the page template

First, we need to create a custom page template. A page template is nothing more than a PHP file with a special commented code at the beginning of the file.

Go ahead an create a new php file and name it “tagcloud.php” or whatever you want. Now put the following at the beginning of it:

<?php
/*
Template Name: Tag Cloud
*/
?>

With this we’re telling WordPress that our tagcloud.php file is a page template and it’s name is “Tag Cloud”.

The basic structure

Now let’s add the basic page structure, header, sidebar and footer. Of course, this depends on the theme you’re using. I’m just going to assume we’re using the Kubrick theme structure for this tutorial. I recommend you open the page.php file of your theme and try to replicate it. The resulting file might look something like this:

<?php
/*
Template Name: Tag Cloud
*/
?>
 
<?php get_header(); ?>
 
    <div id="content" class="narrowcolumn">
 
    </div>
 
<?php get_sidebar(); ?>
 
<?php get_footer(); ?>

That would print an empty page because we haven’t inserted the template tag yet.

The template tag

Now we need to put in the tag cloud template tag: wp_tag_cloud(), which will print the tag cloud. You can find more information on the wp_tag_cloud() template tag in the codex.

Okay, let’s add the template tag:

<?php
/*
Template Name: Tag Cloud
*/
?>
 
<?php get_header(); ?>
 
    <div id="content" class="narrowcolumn">
 
        <div class="tag_cloud">
            <?php wp_tag_cloud('number=0'); ?>
        </div>
 
    </div>
 
<?php get_sidebar(); ?>
 
<?php get_footer(); ?>

Notice that we entered “number=0” parameter, this is because, by default, the wp_tag_cloud() template tag only prints the 45 most used tags, and we want to display them all instead.

Also, we’ve placed the template tag inside a div with a class of “tag_cloud” in case we need to style it later with some CSS.

We’re done with the PHP part, now save your file and upload it to your theme directory (wp-content/themes/your_theme_name).

Creating a new page in WordPress

All we need to do now is create the page in WordPress. To do this, you just have to follow these steps:

  1. Go to the Write » Page section of the admin panel.
  2. Type a descriptive title for the page in the Title field.
  3. Locate the Page Template panel, open it if it’s closed, and choose “Tag Cloud” from the drop-down menu.
  4. Hit the Publish button.

And we’re done. Feel free to post your thoughts and questions in the Comments section.

Making a widget for the Popularity Contest plugin

If you’re a fan of the Popularity Contest plugin like myself and are using a widgetized theme, then you must have noticed that the plugin doesn’t come with widgets that you can easily add to your sidebar. Well… today we’re going to make one.

What we’re going to do is take the basic code for a widget and just put the main Popularity Contest function inside. Sound easy, doesn’t it. Let’s go.

The basics

First of all, you need to be running at least WordPress 2.3 and if you haven’t installed the plugin yet, go to Alex King’s site and download your copy. Then upload it and activate it.

If you’re running WordPress 2.5 then you might need to make some changes as I noted here.

The widget

A widget is nothing more than just a piece of php code. It can be placed inside a plugin file, or inside the functions.php file of your theme. For this tutorial we’re going to put it inside the functions.php file.

This is the basic widget code:

function widget_popular_contest($args) {
    extract($args); ?>
 
    <?php echo $before_widget; ?>
 
    <h2>Popular Articles</h2>
    <ul>
        <?php akpc_most_popular(); ?>
    </ul>
 
    <?php echo $after_widget; ?>
<?php
}

The important part being the popular constest plugin function, which will print our ten most popular posts of all time:

<?php akpc_most_popular(); ?>

Then we need to hook the function, so WordPress knows it is a widget:

register_sidebar_widget('Popular Articles', 'widget_popular_contest');

This might be enough, but we want to make sure the popularity contest plugin is installed, otherwise we risk to get a nasty WordPress error if we decided to deactivate the plugin. So let’s wrap our latest bit of code around the following conditional statement:

if(function_exists('akpc_most_popular')){
}

What this does is checking if the akpc_most_popular() function exists, which would mean that the plugin is there and it has been activated.

Wrapping up

That’s it, we’re all set but just to make sure here is the complete code:

function widget_popular_contest($args) {
    extract($args); ?>
 
    <?php echo $before_widget; ?>
 
    <h2>Popular Articles</h2>
    <ul>
        <?php akpc_most_popular(); ?>
    </ul>
 
    <?php echo $after_widget; ?>
<?php
}
 
if(function_exists('akpc_most_popular')){
    register_sidebar_widget('Popular Articles', 'widget_popular_contest');
}

The End!

Now you can go to your widgets page and add the widget to your sidebar.

Styling the people’s name in your comment replies

You may have noticed that many people use the syntax @name in blog comments for addressing messages to a specific person. Maybe you’re one of them. In this tutorial we’ll learn how to style that piece of text differently so it stands out better.

The Function

First, we’re going to create a function in the functions.php file of our WordPress Theme. This function needs to find the specific piece of text ‘@name’, where name can be anything. Our best option here is using a regular expression. Here it is:

function atPeople($comment){
    return preg_replace("/@([^:]*):\s/", "<span class=\"atPeople\">@$1: </span>", $comment);
}

Pretty simple eh! What this does is finding an @ symbol followed by text and then a colon “:”. For example: “@john:”. Then it replaces that for a span object that we can easily style later.

The Hook

Creating the function is not enough, we need WordPress to call that function with every comment. That’s where the hook comes in:

add_filter('comment_text', 'atPeople');

That little piece of code just tells WordPress to apply our function to the comment text. It also needs to be in the functions.php file, by the way.

The Styling

Ok, now we’re ready to style our span object, which is the easier part. You can do whatever you want with it, you can make it bold, change it’s color, make it bigger, the possibilities are endless. We’re just going to make it bold and red. Here we go:

.atPeople{
    font-weight: bold;
    color: red;
}

And that, of course, needs to go at the end of the style.css file of your WordPress theme.

That’s it, hope you enjoyed this tutorial.

Customize the ellipsis in your trackbacks

You may have noticed that WordPress adds a “[…]” before and after every trackback text. I believe this to be kind of ugly, so I came up with a solution to replace them for something else.

My solution consists of adding this function to your functions.php file:

<?php
 
// Prettier Trackbacks Function
function prettier_trackbacks($comment){
    return str_replace("[...]", "...", $comment);
}
 
// Hook the function
add_filter('comment_text', 'prettier_trackbacks');
 
?>

What this function does is, it searches for “[...]” and replaces it for just the ellipsis “…”.

If you wanted to just get rid of the whole thing altogether you would replace the ‘return str_replace…’ line with:

return str_replace("[...]", "", $comment);

If you don’t feel comfortable with code you can also download the plug-in:

Prettier Trackbacks

That’s it for the first tip, hope you enjoyed it.

P.S: By the way… this will also replace any “[...]” in regular comments. But it is very unlikely that anyone will write that in a comment.