Category Archives: WordPress

Attached Images in WordPress using the_post_thumbnail

I’ve been working with WordPress for years now, and I’ve always struggled with an easy way to display an image that’s attached to a post in a list of posts. I didn’t say it wasn’t possible, just not easy. In the past I’ve used plugins, like "The Attached Image", or hacked my way around the issue. While these methods worked, they weren’t ideal, and any time you can avoid using plugins, the more healthy your WordPress site will be.

I was delighted then, to find that WordPress 2.9+ comes with a few new functions designed specifically for working with images attached to posts. Specifically, the_post_thumbnail works wonders. Here’s how it works:

Add Thumbnail Support

First, you have to activate post thumbnails for your theme. Open functions.php, and add this line somewhere near the top:

add_theme_support('post-thumbnails');
set_post_thumbnail_size(224, 126, true);

The first line adds thumbnail support to your theme. The second line overrides the "thumbnail" settings in your WordPress admin panel. The three values passed here are image width, image height, and the crop flag. If you set the crop flag to true, WordPress will automatically re-crop images so they’re not distorted.

Next, open any of your existing posts. You’ll be happy to find a new box in the right column, titled "Featured Image". You can then use the standard WordPress media tool to either upload a new image, or select an image from your site’s Media Library. Once you’ve associated a featured image with a post, the next step is adding it to your templates.

Insert Thumbnails in Your Theme

Locate the loop where you’d like thumbnail images to appear, and insert the following code:

the_post_thumbnail();

This will insert a full image HTML element, with the option to pass an array to specify dynamically generated attributes, like the image’s alt or title text.

Have More than One Size? No Problem!

Say you want to feature two thumbnail sizes on your site. Switch back to functions.php and add this code, below the code we added earlier:

add_image_size('thumbnail-50', 50, 50);

This cuts an additional image at 50×50 every time an image is uploaded to the WP Media Library. You can add as many sizes as you’d like. You can then add this call in any of your templates:

the_post_thumbnail('thumbnail-50');

Here you’re just passing the name of the thumbnail you assigned in functions.php, so WordPress knows which thumbnail to use. When the_post_thumbnail() is called with no argument, it will use the default size originally set in set_post_thumbnail_size().

There’s a lot more you can do with these new functions, including setting up conditional PHP during loops to display a larger image first, with smaller images for the second and subsequent posts, for example. I encourage further reading at the WordPress codex:

WordPress Codes: the_post_thumbnail()

Advertisements

Its like rejuvenation

I couldn’t resist the temptation to blatantly quote Howard Stern whack packer Blue Iris, as the phrase describes my recent adventures in web design perfectly. It had been way too long; way too long since I’d put myself back in student mode, way too long since I’d let HTML 5 and CSS 3 take shape without paying too much attention, and way too long since I’d posted here. So without further ado, lets take a look at what’s happened in web design over the past six months:

  1. Zeldman released Designing with Web Standards, 3rd Edition.
  2. HTML 5 and CSS 3 support gain traction.
  3. WordPress 3 set to drop any day now.
  4. The BIG Web Show launched.
  5. jQuery still rocks.

Lets take them one at a time:

1. Zeldman has released Designing with Web Standards, 3rd Edition.

The king is back. And this time he’s got a sidekick. That’s right, Jeffrey Zeldman released the 3rd edition of the book that changed the web industry, and he signed up Ethan Marcotte as his trusty co-author this time around. I just blazed through the book in a week, and I’m gearing up for a second run-through. Needless to say, not only will this book give you a rock-solid foundation for building modern web sites, its been updated with current technologies in mind, including new kids on the block, HTML 5 and CSS 3. Also, a special treat this time around is a companion volume, Developing with Web Standards, released simultaneously. Author John Alsopp picks up where Zeldman leaves off, providing the practical solutions to Zeldman’s powerful theory. I’m giving myself a bit of time to digest Designing with Web Standards prior to diving into Developing, but look for a full review of Designing to come over the next few weeks here at Withinsight. All I can say for now is, bravo.

2. HTML 5 and CSS 3 support gaining traction.

HTML 5 and CSS 3 not only offer all kinds of fun new goodies for web designers and developers alike, they’re now starting to gain real support. In addition to the support already provided for new HTML elements and CSS properties in browsers where you’d expect it like Firefox, Chrome and Safari, it appears that IE9 has completely jumped on the bleeding-edge standards wagon. While the finalized specs are still years off, if all major browsers support them with the release of the next version of IE, we’ll be able to start using them reliably very soon. Actually, you already can, but more on that in bullet 4. If IE9 really does support HTML 5 and CSS 3 as well or better than other modern browsers, this may just be the kick that IT departments and large corporations need to drop their “IE6 fo’ life” mantra. Exciting times indeed.

3. WordPress 3 is set to drop any day now.

WordPress 3 will support multi-site installations, meaning you can install WordPress once and create multiple blogs from the single installation. I’m so happy I think I just made a mess in my pants. This means no more upgrading multiple installations of WordPress with each release, centralized plugin management, and huge swaths of citizens rejoicing in the streets for weeks on end. Well, maybe not that last part, but this one feature alone would be enough for me for one upgrade. I’ve played with the beta 2 release a bit, and its super-simple to setup multiple blogs, and basically acts like WPMU did, where you can select subdomains or subdirectories for all your additional blogs. The potential is making me dizzy. Roo-haa.

4. The BIG Web Show launched.

Zeldman’s The BIG Web Show launched recently, and just concluded its third episode this past Thursday. If you like web design, pay attention. Episode 2 featured Jeremy Keith as a special guest, promoting his latest book, HTML 5 for Web Designers, which is slated to drop in June. Remember when I mentioned using HTML 5 and CSS 3 now above? Good! In The BIG Web Show, episode 2, Keith explains how you can start supporting the semantics of HTML 5 now by using standard class names for your divs that correspond to the HTML 5 elements. Not only does it make transitioning in a future redesign easier, it makes explaining your classes to other designers or developers 100 times easier when you hand off your work because you can just point them to the spec. Fantastic. Also, kind of a sub-bullet here, HTML 5 for Web Designers is the first book from A Book Apart publishing! I’m overjoyed with this new publishing company and will likely gobble up each and every offering they proffer from here until infinity.

5. jQuery still rocks.

I really only started working with jQuery personally about a year ago, and since then the library has really gone full-blown as the hands-down most popular JavaScript library in existence. Not only has it been included in the download of WordPress for a while now, its hosted by Google in its compressed form, which means if you link to the Google version and your site visitors already visited a site that also links to the Google version of jQuery, they don’t have to download it again. In addition, all the JavaScript examples in Designing with Web Standards, 3rd Edition are in jQuery, because it just makes JavaScript so much more concise and is easy for the uninitiated to pick up, having a syntax very similar to CSS selectors.

So that’s it for now, stay tuned for more frequent updates as I’m completely turned on by the impending release of WordPress 3 and impending web standards developments. This truly is an exciting time to be a web developer. Cheers!

How to Setup a Page-Driven Nav in WordPress 2.7

I’ve been working with WordPress for years now, and I thought it might be a good time to start sharing my knowledge of WordPress best practices.  One item that I think a lot of people just getting started using WordPress might find handy is how to build a navigation that is driven by pages.  Having a navigation driven by pages has numerous benefits, including having the nav written out as an XHTML compliant unordered list, being able to include or exclude any pages you’d like, being able to sort the list items to your preference, and being able to style the current page’s nav button differently.

Create those Pages

The first thing you need to do to setup a nav driven by pages is create the pages themselves.  The title you give the page will be the text that appears in the nav.  Also note that by default the nav items will be sorted alphabetically, but you can prioritize them setting the “Order” field from within each individual page.

The Magic of Template Tags

After you’ve created all the pages you’d like to include in the navigation, all that’s left to do is add the template tag to your template (usually in header.php).  The template tag that lists pages in WordPress is, you guessed it, wp_list_pages. Here’s a sample template tag included in my header.php file that passes a few parameters to the function:

<?php wp_list_pages('include=2,7,9,11&title_li='); ?>

The above block of code includes an opening php statement <?php, the function call wp_list_pages('');, and the arguments to be passed to the function include=2,7,9,11 and title_li=.

Let’s take a look at the two arguments I passed to the wp_list_pages function, starting with include=2,7,9,11.

This tells the function I’d like to include only pages with the id’s of 2, 7, 9 and 11. To find the page id’s that match your specific pages, go to your pages>edit screen and hover over the link for the title of the page, and (if you’re using Firefox) look at the bottom of your browser. At the end of the link you’ll see something like post=7. The number here is your page id. Plug in the page id’s for any pages you’d like to include, and you’re good to go!

The other argument I pass to the wp_list_pages function is to remove the title that would appear by default. By passing title_li= you’re essentially saying “set the title to blank”, and the function does not return a title list item. Generally you won’t want the title, which is up one level in the document tree, to appear if you’re making a navigation that you’ll end up floating to the left with CSS.

The ampersand between the two arguments just allows you to string together multiple arguments. You can string together as many as you’d like to further develop your own custom WordPress queries using any of the further options detailed on the WordPress.org wp_list_pages template tag page.

Check out the Coolness

The last, and probably most worthwhile thing about building your nav in WordPress using pages is that while navigating your site, the list will be auto-updated with a class that allows you to style the current page’s button to look different than the other nav buttons.  After you’ve got your nav set up and working, visit one of the pages and then view the page source.  You’ll see the class of current_page_item applied to the list item for the page you’re currently on, automatically generated by WordPress for each page.

Now just start styling your way to a dynamic WordPress page-driven navigation! If you need more info on the CSS required to float a list to the left that creates a horizontally oriented navigation out of an unordered list, check out this tutorial at 456 Berea St.

I hope this can help you to build your own navigation, and take it even further using the WordPress.org template tag page.

SXSW and jQuery

So right about now I’m wishing that if I could be anywhere, it would be at SXSW (South by Southwest).  For those of you who don’t know, its about the coolest festival on the planet.  And I don’t know from experience, just from colleagues and coworkers and podcasts and industry moguls giving me an earful.

In addition to being a hotspot for web design, SXSW boasts an impressive musical lineup each year, and this year I’ll be disappointed that I’ve missed The Everyday Visuals, Madi Diaz, and the undisputable heavyweight of soul, Miss Erykah Badu.

I’ve been hearing about it for weeks, from Paul Boag blabbering about it on his Boagworld podcast, to having to postpone projects with colleagues who are attending, to CSS guru Eric Meyer tweeting, “If you’re not going to SXSW, tweet like you’re there.  Nobody will know the difference.”  Yeah, that almost makes up for not being able to attend.

But alas, I am not one to linger, and the time spent here at home has given me the opportunity to start exploring jQuery, which was recommended to me by Alex King, famed author of the WordPress Popularity Contest plugin, and another item that Paul Boag has been going on endlessly about for months now.  I finally broke down and downloaded the library and started playing with it.

From my first impressions, Paul has reason to be going on endlessly.  It seems that the potential of what a web designer or developer can accomplish with the JavaScript library is in fact endless.  The first item that caught my eye was the fact that on the jQuery homepage they offer the expanded, developer version of the library, along with the compressed, production version.  I was immediately reminded of the hours I’ve spent testing the best method to minify, compress and serve my Prototype and Scriptaculous libraries.  jQuery does this for me?  Fantastic.

Second, I was really impressed with the quality and quantity of documentation.  Compared to Prototype, jQuery blows it out of the water in terms of a working online manual.  I think I’ve officially moved the “Prototype and script.aculo.us” book to the back of my “must read” list.  I’ve actually read the first half of it already, but it was cryptic and would have required re-reading on my part to fully absorb the material.  jQuery is the complete opposite.  There are video tutorials explaning the beginner steps.  Video tutorials.

The last thing about jQuery that really hooked me was the ease with which a web designer can pick up the library.  A lot of the arguments you pass to the library are the same as in CSS.  So if you’re looking for a div with the id of conference, you pass (“#conference”) as the argument.

It seems like its going to be really easy to quickly get up to speed with the library, and that it has a lot of power in terms of what you can do with it.  If you’re interested, check out the jQuery site, the jQuery UI site, as well as some of the video tutorials. Really, really, really cool stuff.

Installing WordPress MU on Mac OS X Leopard

I’ve run through this process a few times now, so I thought I’d document my steps for anyone who’s interested in setting up the multi-user version of WordPress on their local box for testing purposes.  The power of the multi-user version of WordPress is impressive, especially when combined with BBPress for forums, and the teetering-on-official-release BuddyPress for social aspects.  Ready to dig in?  Lets go.

The first thing you need to ensure prior to installing WordPress MU locally is that you have the underlying technologies installed.  WordPress and WordPress MU run on LAMP, or in this case MAMP.  There are all-in-one packages out there that install all three for you, and OS X does come with versions of Apache and PHP, but we want to learn how to get our hands dirty and be able to fix anything ourselves in times of crisis, right? So we need to make sure you’ve got Apache running, MySQL installed with a dedicated database setup, and PHP installed.

Turning on the Apache Web Server

First, we’ll tackle Apache.  This sentence will probably take longer to write than it will for you to turn on Apache on your Mac.  Go to System Preferences > Sharing > Web Sharing.  Checking of the “Web Sharing” checkbox here toggles the Apache server.  If you ever need to restart Apache, its as easy as coming in here, unchecking the “Web Sharing” checkbox, and checking it again.  Cake.

Installing MySQL

On to MySQL.  You’ll need to download the most recent version of MySQL, which can be found at the MySQL downloads page. Click “downloads” under the MySQL Community Server section.  Scroll down to the “Mac OS X (package format)” link and click.  Here is where you’ll have to ensure you download the proper package based on your Mac.  I chose the 10.5 (x86) since I’m running an Intel MacBook Pro, which ias the x86 processor. After you determine which package suits your Mac, click the “pick a mirror” link, and if you’ve never downloaded anything from the MySQL site before, you’ll have to register quickly.  Once you’ve registered and downloaded the dmg (named mysql-5.1.31-osx10.5-x86.dmg in my case), you’re ready to run the installer.

Once you’ve opened the dmg, you’ll see two .pkg files we’ll be interested in.  First, run the installer pkg file, which will walk you through a simple install.  After the initial install you’ll want to launch MySQLStartupItem.pkg, which will ensure that MySQL starts each time you restart your Mac. You’ve now got MySQL installed on your Mac!  Note the install location, as we’ll need that later on to create the database for WordPress MU.  Mine installed at /usr/local/mysql/bin/mysql.

Another item worth mentioning is that working with MySQL, PHP and Apache requires you to have access to a lot of OS X’s hidden files.  I recommend a great OS X app called FileXaminer, which I read about in MacWorld a while back.  FileXaminer lets you browse all the hidden files in Finder, and chmod the permissions on files and folders directly from Finder, rather than the command line.  Definitely a great solution for 10 bucks.

Installing PHP

The final piece of our MAMP stack is PHP.  PHP installation is fairly straightforward, and the best package online is located at Entropy’s PHP download page. There’s a box on this page titled “PHP 5 on Mac OS X 10.4, PPC and Intel”, and you can select the “PHP 5.2.4 for Apache 2” package.  Its definitely worth reading through this page first, but most users will have the default setup of Apache, and won’t need to make any changes prior to running the install.

After running the entropy installer, you can run a test to make sure everything went well.  Create a file titled test.php, and stick the following code in it: <?php phpinfo() ?>. Put test.php in your /Sites folder (/Users/yourusername/Sites), and then open up http://10.0.1.2/~yourusername/test.php.  The IP used in this example is found in System Preferences > Sharing > Web Sharing.

The phpinfo function is a great way to quickly check all the settings of your PHP install, so save this test file for reference in the future.

There’s one final tweak to PHP that’s really a best practice.  You’ll want to navigate to your php.ini file, and open it in your favorite text editor.  My php.ini is located at /private/etc/php.ini.  Make a duplicate of this file (sometimes the original will be called php.ini.default, so make a dup called php.ini).  Once you’ve opened the php.ini file, search for “register_globals = On”, and switch it to register_globals = Off”.  Also, search for “magic_quotes_gpc = Off” and switch it to “magic_quotes_gpc = On”.  In the php.ini file, all lines that start with a ; are commented out, so you’ll want to search for these two lines that are not commented out and then make the changes.

Save the changes in php.ini, then restart Apache in System Preferences.  Then open your test.php file again, and look for the changes to make sure they were made.

Installing WordPress MU

Finally, its time for the money melon.  Download the latest version of WordPress MU from the download page.  Unzip the package and stick it in your /Sites directory, and rename (I chose “wpmu”).  The first thing you’ll want to do before attempting to install WordPress MU is to open the README.txt file that is in the root directory of the unzipped WPMU package.  You’ll want to read this carefully and cater the specific files you your specific install case, but they basically touch upon the php.ini file that we’ve already edited, and the httpd.conf file, which is Apache’s root config file.  I found mine located at /private/etc/httpd.conf.  You can find a better understanding of the Apache httpd.conf file, the directives contained within, and an explanation of the .htaccess files you can use to override the httpd.conf file in your local sites at the Apache web site.  I found that after reading a few short pages here, that the Apache config file cascade is very similar to the cascade of CSS files and rules.  Cool stuff.

Creating a MySQL database

Once you’ve read through the README.txt and made appropriate changes to your php.ini and httpd.conf files (and taken decent notes, hopefully), you’re ready for the install.  Since you’ve already got the files unzipped in your /Sites directory, the next step of the install is creating the database. Open the Terminal application (Applications > Utilities > Terminal), and type the following command:

/usr/local/mysql/bin/mysql -u root -p

where the path matches the MySQL path I mentioned to remember earlier.  The -u root tells MySQL that you want to login as “username root”, and the -p tells MySQL to prompt you for a password. If you’ve never logged into MySQL in terminal before, the username for root will either be root or blank.  After you’ve successfully logged into MySQL, you’ll know as the command prompt will have changed to:

mysql>

To create a database, type the following command:

CREATE DATABASE wpmu;

where wpmu is the name of the database.  You can name the database whatever you’d like, but make sure to follow it with the semi-colon, and remember the name of your database.

While we’re in here, its probably a good idea to change your root username.  Type the following command:

UPDATE mysql.user SET Password=PASSWORD(“new password”) WHERE User=”root”;

Replace the new password with your desired password.  Once we’ve created the database, and updated the root MySQL user’s password (and noted both), we can exit MySQL by typing:

exit

Running the WPMU Installer

You can now open the index.php from your wpmu folder in your web browser.  It may tell you that you have to change the permissions on a few folders prior to running the install.  If this occurs, it is extremely easy to modify the permissions using FileXaminer.  The two folders you’ll have to mod are the root /wpmu folder and the /wp-content folder, changing the permissions on both from 755 to 777.  After you’ve made these changes, refresh the index.php file, and enter the proper information.

Since WPMU doesn’t allow you to install at “localhost”, and you have to use “localhost.localdomain”, I had to make a change in my hosts file as well.  The file is located in /private/etc/hosts, and I changed:

127.0.0.1 localhost

to

127.0.0.1 localhost.localdomain

and resaved the file.  Also note that I set the database location to “localhost.localdomain”.  The other information on the install screen should be pretty simple; the database name and password we just created in MySQL.  Once you’ve filled out the form, submit and you should be looking at a nice, fresh, local install of WPMU.

If you do get stuck, the WPMU Forums are a big help, as most likely users have run into your same problem. The steps above worked for me, but there may be variables with your certain configuration that you’ll need answered in the Forums.

Good luck, and happy WPMU’ing!

UPDATE 3/4/09: If you’d like to configure OS X Leopard to host multiple local WordPress instances, follow this great tutorial at O’Reilly.  I’ve spent hours piecing together solutions from various articles, but this O’Reilly article sums it up great.  Basically, I’ve now got WPMU running locally at test.wpmu.local, and WordPress running locally at test.wp.local.  Apache’s Virtual Hosts are really powerful, and essential if you’re going to be working on multiple client websites that run on WordPress.