Beginning WordPress Development: A Look at Common Functions

Nov 15 2010 by Amber Weinberg | 38 Comments

Beginning WordPress Development: A Look at Common Functions

WordPress is a great blogging and CMS platform. It’s easy to use and customize, and there’s basically nothing you can’t do with it. If you haven’t used WordPress, give it a try by installing it on your own computer using a web server package like xampp or WampServer. You’ll need access to WordPress in order to follow along with this guide.

In this guide, we will take a look at some common functions in WordPress for use in custom WordPress theme development.

Introduction

As a developer, one of my favorite things about WordPress is its built-in functions, which allow you to easily manipulate and extend WordPress with just a few lines of code.

WordPress functions are an essential component of WordPress theme development; once you understand how they work, it’s easy to create your own custom WordPress themes.

Navigation

The most popular sets of functions in WordPress are navigation-related functions. For navigation menus, a popular function for dynamically generating them is to use the wp_list_pages WordPress function. Another method for dealing with site navigation was recently introduced in WordPress 3.0: the wp_nav_menu function.

We’ll talk about these two functions, starting with wp_list_pages.

Listing All Pages

If you want to list all of the pages you’ve got (note that pages and posts have different meanings in WordPress vernacular), there’s a simple function for that called wp_list_pages. When used without any parameters, it will list all of your pages in alphabetical order.

<?php wp_list_pages(); ?>

Listing Specific Pages

As with many WordPress functions, the wp_list_pages function takes several parameters. For example, the include parameter allows you to list specific pages by referencing their page IDs, separated by commas (,). The following example will only list two pages (the pages have IDs of 4 and 5).

<?php wp_list_pages('include=4,5'); ?>

Excluding Specific Pages from a List

You can also exclude specific pages using the exclude parameter:

<?php wp_list_pages('exclude=4,5'); ?>

Sorting Pages

As discussed earlier, the default sorting order of wp_list_pages is alphabetical. You can, however, change the order of the listing using the sort_column parameter. The sort_column parameter can have 1 of 7 values:

  • post_title – Sort alphabetically (default value)
  • menu_order – Sort by page order
  • post_date – Sort by date of creation
  • post_modified – Sort by time last modified
  • ID – Sort by page ID
  • post_author – Sort by the page author ID
  • post_name – Sort alphabetically by post slug

Here is the code for sorting by creation date instead of the default alphabetical order:

<?php wp_list_pages('sort_column=post_date'); ?>

Specifying the Depth

Pages can have subpages, and subpages can have subpages. What if you only wanted to list top-level pages but exclude their subpages? Controlling the depth works great when using it to generate dropdown menus with submenus.

You can use the depth parameter like so:

<?php wp_list_pages('depth=1'); ?>

Enabling WordPress 3.0′s Navigation Menu Feature

If you’re wanting absolute control over your navigation, using WordPress 3.0′s new menu function, wp_nav_menu, is the way to go. With this function, you can add categories in menus, submenus and even insert external links into navigation menus.

To take advantage of the built-in navigation menu functionality, first you need to enable it in your theme. In your functions.php file located in the theme directory, you’ll need to add the following:

<?php add_theme_support( 'menus' ); ?>

Next, place the following code in the location where you want the menu to show on your site (this could be in your standard theme template files such as header.php or single.php):

<?php wp_nav_menu( array('menu' => '[Menu Name]' )); ?>

Replace [Menu Name] with what you want your menu to be named.

You’ll then need to navigate to Appearance > Menus and create your menu with the same exact name. Everything from there is simply drag and drop!

Displaying Blog Information

We’re moving on to getting and working with information about the blog. WordPress has a function for getting and printing your WordPress blog information called bloginfo. This is a good function to use for themes that will be used in multiple domains. There are many parameters you can use for bloginfo; to find all of them, read the bloginfo WordPress Codex documentation.

Getting the Site’s URL

Let’s say your site’s URL is http://example.com. If you want to print this out in the source, you can use the url parameter.

<?php bloginfo('url'); ?>

This works great for absolute link references. For example, if you wanted to reference your logo (let’s say the file name is logo.png) that is in a directory called images, you would do the following:

<img src="<?php bloginfo('url'); ?>/images/logo.png" />

The above outputs:

<img src=" http://example.com/images/logo.png" />

Getting the URL to the Current Theme

To grab the current theme directory’s URL, you can use the template_url parameter. This makes your WordPress themes more flexible so that when you change the domain name or use it in multiple domain names you don’t have to worry about changing anything that references the theme’s location. You can use this parameter a number of ways, such as for referencing custom external stylesheets, images, and JavaScript libraries that are inside the theme directory.

<?php bloginfo('template_url'); ?>

Getting the URL of Your RSS Feed

The bloginfo function can also be used for getting other URLs. For example, if you want to grab the RSS feed URL for your site, you can use the 'rss2_url' parameter:

<?php bloginfo('rss2_url'); ?>

If you wanted to create a link to your RSS feed, you could use the following:

<a href="<?php bloginfo('rss2_url'); ?>">Link to RSS feed</a>

Working with Content

The WordPress loop is used to display your posts. A basic loop looks like this:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php endwhile; endif; ?>

Not much to look at right now, but it’s what’s going to go inside the loop that really matters.

Querying Posts

First, let’s look at the most important function that goes inside the loop called query_posts. query_posts only needs to be used if you want to display information from another page, post or category than the one the user is currently on. For example, on the front page (controlled by index.php, home.php, or front-page.php theme template files) you could use query_posts to show the three newest posts in the hypothetical category called Featured.

You use query_posts not only to show different kinds of content, but how much content matches the query as well.

Displaying Posts in a Category

Keeping with our Featured category example above, here’s how we’d show the three newest posts from the Featured category:

<?php query_posts('category_name=Featured&posts_per_page=3'); ?>

Aside: Passing Multiple Parameters into Functions

Notice that we passed two parameters into the query_post function. The parameters we passed were category_name and post_per_page.

In functions with more than one parameter, you can pass multiple parameters all at once by separating them with an ampersand (&). You can pass as many parameters as you want. Doing so allows you to increase the specificity of your desired outputs.

Excluding Posts

Similar to wp_list_pages, query_posts has a way to exclude items from being displayed. To do so, you just place a minus character (-) in front of the ID of the items you want to exclude.

For example, let’s say you would like to list all posts except posts from two categories with category IDs of 97 and 34. You could use the cat parameter (which is typically used to display only posts within certain categories) for query_posts:

<?php query_posts('cat=-97,-34'); ?>

Displaying Common Information

Now let’s move on to some more functions we can use inside the loop. Many of these functions can only be used inside the loop and may not work if used outside of it.

Display the title of the post:

<?php the_title(); ?>

Display the URL of the post:

<?php the_permalink(); ?>

Display the content of the post:

<?php the_content(); ?>

Display the excerpt of the post:

<?php the_excerpt(); ?>

Display the category of the post:

<?php the_category(); ?>

Display the tags used in the post:

<?php the_tags(); ?>

Display the time the post was published (uses PHP date formatting as a parameter):

<?php the_time(); ?>

Working with Custom Fields

One of the most powerful functions that WordPress has that seems to take developers a long time to learn is the use of custom fields. Custom fields allow users to add custom name/value pairs typically used for post metadata. For example, users can add a post_thumbnail_url key that has a URL value pointing to the thumbnail image.

Users can add custom fields while they are creating posts and pages in Posts > Add new or Pages > Add new.

Working with Custom Fields

I’ve used custom fields for everything — from post thumbnails and changing the background of the individual post to adding custom link and layout areas. It becomes very powerful once you’ve learned it properly.

Getting custom fields can be done from inside or outside of the loop. If you use it outside the loop, you have to reference the ID of the post or page you want the custom field name/value pair from.

Using Custom Fields to Display Image Thumbnails

Let’s say you want to display an image thumbnail in a post.

First, you must create a new post (Posts > Add new). Under the Custom Fields fieldset, type Thumbnail into the Name field and a URI for the Value field. Then publish the post.

Wherever in the loop you want the URI to be displayed, simply use the echo statement to output the result of get_post_meta (which is a function for getting custom fields).

<?php echo get_post_meta($post->ID, 'Thumbnail', true); ?>

To use get_post_meta outside the loop, change $post->ID to the ID of the post. For example, here’s how to print the URI of the thumbnail image for the post with ID of 6.

<?php echo get_post_meta(6, 'Thumbnail', true); ?>

Since we want to display an image, what we actually need to do is use the echo statement inside the src attribute of an img element:

<img src="<?php echo get_post_meta(6, 'Thumbnail', true); ?>" />

The code from above should output the following:

<img src="/images/thumbnail.jpg" />

Related Content

About the Author

Amber Weinberg is a freelancer with over 10 years of experience. She’s the founder of codesnipp.it, a social site for developers. She specializes in clean, semantic and valid 1.0 Strict XHTML, CSS and WordPress development. She also writes a web development blog on her portfolio site at www.amberweinberg.com.

38 Comments

Omer Greenwald

November 15th, 2010

Excellent post presenting the basic wp functions. I’m not sure that displaying thumbnail using custom fields is the best example though, because it is much easier to use the post thumbnail feature for this (since wp 2.9).
Displaying posts in customized order can be an example of using custom fields.

Pritam

November 15th, 2010

The post is good for a quick reference, but some of the tags such as bloginfo(‘url’) are dated. Now, one has to use home_url() for getting the same info.

Adam

November 15th, 2010

Thanks – a handy roundup/reference.

paul

November 15th, 2010

I suggest using the native WordPress post thumbnails instead of a custom field.
Just enable them in functions.php

add_theme_support( ‘post-thumbnails’ );

then you can do

paul

November 15th, 2010

then you can do

Ahmad

November 15th, 2010

Level one WordPress Knowledge very good explained article
Waiting for level 2 :-)

Giuseppe

November 15th, 2010

Great post Amber!!! I must start to work on wordpress to customize a portal and this post is what I need. Thanks!

Jacob Gube

November 15th, 2010

@paul: I think it was just an example for a talking point, because using image thumbnails as an example is good for explaining what custom fields can really do. And as for using post-thumbnails that’s native to WordPress, it’s a good idea, but I personally like using custom fields instead of it (merely a preference for my own sites — but I agree that if I was developing a custom theme for someone else or releasing a freebie theme, I’d use post-thumbnails).

David

November 15th, 2010

I’ve used custom field for thumbnails in my templates several times, but many users seem to have problems with it not being so straightforward.
Wordpress 2.9 has the post_thumbnail feature http://codex.wordpress.org/Function_Reference/the_post_thumbnail but it is less flexible.
Are there better solutions?
Anyway a very good post for those new to wordpress theming!

Amber Weinberg

November 15th, 2010

@Pritam That’s not true, you still use siteurl

Jacob Gube

November 15th, 2010

@David: Yeah, for user-friendliness, post-thumbnail would be nice. Because using custom fields, you need to specify the image’s URI, and so doing that doesn’t really integrate well with WP’s image upload functionality.

But on DI and SR, we don’t use the default image upload functionality; we host file assets on a different server so custom field works well. You can see it in action on designinstruct.com, the lead-in images uses a custom field, almost exactly like how Amber described. Custom fields are also used for the RSS feed images on that site; the RSS feed on DI is custom, it doesn’t use the WP RSS feed, so custom fields was also nice for that.

The trade-off is that it’s not as user-friendly.

Young

November 15th, 2010

@Paul & Jacob: I also prefer using custom fields for my own portfolio, for the complete control it gives me. For example, on the portfolio section of my site, I wanted the thumbnail to be different files (not included in the post itself), styles and dimensions, and it was just easier to have a custom field tied to each post in terms of code manipulation. I’m sure there’s a way to do this using the plugin, though.

@amber: As far as the article goes, this is an excellent list. I made a similar list when I first taught myself WP.

Fred

November 15th, 2010

Amber thank you for this concise article which some of the areas that I really should be getting into. Great reference document.

Heath Waller

November 15th, 2010

A really nice summary of common functions for a beginner like me. WordPress can feel (to me) overwhelming at times, so getting information in bite-like chunks is really useful at this stage. Thank you, Amber.

Jacob Gube

November 15th, 2010

@Young: Sweet, that’s what I was trying to say — control and flexibility, which is great if you’re a WP developer. And pretty sure lower resource overhead than using post-thumbnails (maybe not though, I haven’t done any real app profiling to compare custom fields performance versus post-thumbnails performance — but intuitively, it makes sense). And, to me, entering a URI is quicker for our set-up (takes like 3 seconds, I think I can spare that).

Just to summarize, in case new WP devs are reading this and thinking I’m against using post-thumbnails:

1) Use post-thumbnails for thumbnails for your clients and WP themes that you are releasing to the public

2) If you like custom fields better for your personal projects (which is the reason I’m using it for SR and DI) — go for it.

Curtis Scott

November 15th, 2010

Great break down, I wish I’d have read something like this prior to my first WP site. Thanks for sharing!

ValeraZ

November 15th, 2010

Thanks for great post.
Useful summary of functions for wordpress theme dev.

Nabil

November 15th, 2010

Amazing post. One of my goals for 2011 is to create my own WordPress theme. This sure helps me out on the road…

arnold

November 15th, 2010

yup jacob is right on using custom fields…
its much easier to style..

Joffrey

November 16th, 2010

@Jacob
I have used the custom fields within several sites now and enjoy using it. The only thing I haven’t been able to do is giving the images an Alt/Title attribute when using the custom fields. Any idea how to do that?

@Amber
Like your article :) It is good to have an overview of the wonderful WordPress possibilities :)

Harry G

November 16th, 2010

@Amber Weinberg actually pritam is correct. Although the bloginfo method works, home_url() is better as it can handle https domains.

Jacob Gube

November 16th, 2010

@Joffrey: Here’s what I would do if I wanted to give custom field image thumbnails an alt attribute. This one is a preference (but I’ll mention also how you’d do it more “properly” than my preference).

I’m just going off the cuff here, and I’m just going to share the basic logic, so there might be a better way.

Say your custom field is called custom_field_thumbnail. Values assigned to custom fields are actually string data types, so they’re easy to manipulate using PHP.

  1. for the custom_field_thumbnail in the post, I would assign the URI and alt attribute as comma-delimited values. e.g. /images/MyThumbnail.jpg, This is my alt attribute
  2. Script-logic-wise, if there’s only one value, we have just the URI (no alt attribute). If there’s two values, we have both the URI and the alt attribute.
  3. In the theme template files (best if you do this as a custom function in functions.php that you call from your theme template files instead of inline in your template files; easier to maintain your stuff that way), you grab the value of the custom field, place the value/s into an array using the explode PHP function (documentation of explode here). e.g. $thumbnailAttributeArray = explode(', ' [ValueofCustomField])
  4. Then you just do a conditional statement to check if the custom field was assigned two values or not. e.g. if(sizeof($thumbnailAttributeArray) > 1))
  5. If the above is true, then you know that both the URI and alt attribute was assigned. If not, then you only have the URI. Based on that, you generate your img element accordingly.

The above is simple to do — and if you know what you are doing and are familiar with WP’s admin UI — is more convenient than the “right” way to do it.

The “right” way to do it is to have 2 custom fields: one for the URI of the thumbnail and one for the alt attribute text.

Those options above is how I, as a developer, would do it for my personal sites. This is NOT the way I would do it if I was creating a WordPress theme for the public; it’s just not user-friendly and it’s prone to user-errors. For public themes, I would either use the built-in post-thumbnails functionality or dev a custom function/plugin and then give a GUI for it in the Add Post/Add Page GUI if I wanted more flexibility.

EDIT: comma-delimited would not be a good idea because it’s a common punctuation mark. So if your alt attribute was “An image of apples, bananas, and oranges sitting on a table” — the function will fail. So for the delimiter, I would find a character that isn’t used a lot in text, and one that is not an allowed character for file names (because, if you used a hyphen, for example, the function breaks if your thumbnail’s filename is my-thumbnail.jpg). Or you could use a weird character combination for the delimiter, like {!} or something like that.

Joffrey

November 16th, 2010

@Jacob Wow Jacob, thanks for quick and useful reply. I will definitely try this out, been looking for this for quite some time now, thanks! :)

Jacob Gube

November 16th, 2010

@Joffrey: np, I hope that helps. It’s just an idea though, I didn’t write a copy/paste script. But my thinking behind that is that if you’re comfortable enough to use custom field thumbnails, the above idea wouldn’t be hard to implement; probably 20 mins tops for beginning/intermediate PHP devs, including writing, testing, and a little documentation.

hackproject

November 16th, 2010

Nice post Amber, I’ve bookmarked this as its amazing how often I come across a requirement for some code, but forget the exact wording! Many Thanks.

david

November 16th, 2010

Finally stuff that anybody can understand that the a very good way to star up step by step, not putting a bunch of code and saying that does the trick and that’s all… hey what i would like to see it’s how to integrate timthumb since i see that you’re using custom fields to pull up thumbnails that will be greatly appreciated! thanks!! keep it up!!

AJ

December 23rd, 2010

When I looked at this as I was first led to believe that using the_post_thumbnail did not create an extra query so using custom fields would be more costly and hurt performance. After more reading it appears that this is not the case and either method requires an additional trip to the database as the_post_thumbnail isn’t part of the loop. Anyone have any comments or insight?

fiasco

December 31st, 2010

nice post

Alexander

March 4th, 2011

Awesome post which will really help when i start developing my own theme

thank you very much

edie

March 29th, 2011

Thanks for the article. i am a wordpress beginner who need more and more tutorials. i am waiting for next amazing articles.

Petter

July 25th, 2011

This sure helps me creating that first wordpress theme :)

Sebastian

August 18th, 2011

Awesome post, helped me a lot when I build themes

Matt Litherland

September 20th, 2011

Has anyone figured out how to remove the from the anchors. I’m trying to use wp_nav_menus on a HTML5 nav which looks like this:

<a href="" title="" rel="nofollow">Link</a>
<a href="" title="" rel="nofollow">Link</a>

^no . Any help greatly apreciated.

Ashutosh Nigam

November 1st, 2011

very nice post and very important for the users like me…..

rajeev dhar

November 18th, 2011

very good , this is very useful for beginner

venkatesh

October 10th, 2012

Nice article to read for new ones, is there any article for full basics in wordpress

Leave a Comment

Subscribe to the comments on this article.