Author Archive

WordPress Theme Options Overload? A Judgment Call

WordPress Theme Options Overload? A Judgment Call

Lately, while I’ve been busy coding themes for WPBundle, I’ve had to make a few judgment calls. One of the main ones for me is how I wanted to handle the “Theme Options” people have come to know, and quite frankly, expect.

Every theme these days has theme options, and there are a ton of guides on creating theme options. So now instead of it being about actually having the Options page, it’s turned into how many options can you squeeze into your theme.

A Growing Problem

But I see a problem with this. Not only are people resorting to creating custom pages so they can have 10+ tabs on the single page just so they can fit all the options, but they are creating redundant options. Sometimes I think Theme Developers are completely forgetting how huge the Plugin Directory on WordPress is. So when you are creating your theme, is there really a need to have an option to put “Stat Tracking” code? If the user actually wants that option, they can do a quick Plugin search and find over 300 stat plugins.

Making the Most of the Basics.

The point I am trying to make is, why confuse people? By creating these “custom” option pages, not only can you end up confusing the user by giving them a completely different environment, but you end up overwhelming them with options they may have no clue about. So instead of cluttering up the options that really need to be easily changed, with something that has been done hundreds of times in a Plugin, just give them the basics.

I think if someone is really interested in customizing their theme, they will probably already have some knowledge on how to do it. Or just let them ask in the Support forums; that’s what they are for right?

One of the theme’s I’m working on right now only has two options on the Theme Options page (which could really even be one.) So instead of spending an hour rummaging through 100+ different inputs, checkboxes, dropdowns, they can start adding their content almost instantly.

Less is more.


Revisited: Creating Custom Write Panels in WordPress

Almost a year ago (wow, time flies!) I wrote a little tutorial explaining the nuances of add_meta_box in WordPress, and how it can be used to create some nifty Custom Write Panels. It was a nice little script, and still functioned great. I use it on almost all of the projects Liam and I have, and up to this point, it has been great. However, for an upcoming project, I foresaw some problems.

The current way things are set up in the script, it created a new row in the postmeta table for each custom input you included. Because of this, when you wanted to display the results on your theme, you also needed a separate variable for each input. Again, this great, and I never had any problems with it. But what happens when you have more than just one or two inputs? What about 8-10? Then things start getting a little hairy. Not only do you have to create 8-10 separate variables, but it creates a bunch of unneeded entries in the database.

So I decided to revise my script. Although it is only about 15 lines shorter than the previous one, it should function quite a bit faster (although I’ve done no real time trials.) The basic idea of the changes is to use a single row to include all the input fields, instead of one for each. If we store all of the data in a serialized array, we can have one key that holds all of our data. Because there is only one row to retrieve, we only have to define one variable to display our data.

A quick Example

This graphic is just a quick example to those of you who are new to custom write panels to help you see how this technique can be used to improve your experience in WordPress. Click to enlarge.

Things start of basically the same. I’ve slightly altered my meta box arrays (taking out info that never really gets used.) I’ve also added a new variable, $key which will be used to label our new data (among other things.)

Where We Left Off (in functions.php)

Note: Please excuse the code indentions. The WordPress plugin auto-formats it. Sorry!

<?php
/*
Plugin Name: Custom Write Panel
Plugin URI: http://wefunction.com/2009/10/revisited-creating-custom-write-panels-in-wordpress
Description: Allows custom fields to be added to the WordPress Post Page
Version: 1.1
Author: Spencer
Author URI: http://wefunction.com
/* ----------------------------------------------*/

$key = "key";
$meta_boxes = array(
"image" => array(
"name" => "image",
"title" => "Image",
"description" => "Using the \"<em>Add an Image</em>\" button, upload an image and paste the URL here. Images will be resized. This is the Article's main image and will automatically be sized."),
"tinyurl" => array(
"name" => "tinyurl",
"title" => "Tiny URL",
"description" => "Add a small URL of this post that will be used to track tweets, and share the post.")
);

Then, to get it out of the way, lets add our function that actually creates the panels:

function create_meta_box() {
global $key;

if( function_exists( 'add_meta_box' ) ) {
add_meta_box( 'new-meta-boxes', ucfirst( $key ) . ' Custom Post Options', 'display_meta_box', 'post', 'normal', 'high' );
}
}

Same exact thing as before, just used our $key variable to label the title.

Displaying the Write Panels

The next part is pretty similar as well. This is what we use to build the meta boxes. Like I said, not much changes. I’ve just removed some extra code that wasn’t needed (checking for standard values, which was removed from the arrays) and I also changed the way I setup the nonce.

<?php
function display_meta_box() {
global $post, $meta_boxes, $key;
?>

<div class="form-wrap">

<?php
wp_nonce_field( plugin_basename( __FILE__ ), $key . '_wpnonce', false, true );

foreach($meta_boxes as $meta_box) {
$data = get_post_meta($post->ID, $key, true);
?>
<div class="form-field form-required">
<label for="<?php echo $meta_box[ 'name' ]; ?>"><?php echo $meta_box[ 'title' ]; ?></label>
<input type="text" name="<?php echo $meta_box[ 'name' ]; ?>" value="<?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?>" />
<p><?php echo $meta_box[ 'description' ]; ?></p>
</div>

<?php } ?>

</div>
<?php
}
?>

Now I’m using WordPress’s wp_nonce_field to create a nonce. This time it is outside of the foreach loop, because we clearly only need one! (Not sure what I was thinking before.)

As I mentioned before, I took out some code to check for default values, and instead replaced it with a $data value. This looks for our single meta row, with our defined key, and fills the input with any necessary data.

Saving the Data

The final part, where we save the data, is what got changed the most. The basic idea is to loop through our original $meta_boxes array, creating a new array to hold the values. In English: for each array in $meta_boxes, get the value of the input field, and add it to a new $data array.

So now we have a single array. Check out the code below:

foreach( $meta_boxes as $meta_box ) {
$data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ];
}

Not too bad right? In the function, we also need to verify the data. Since I have a better understanding of how the nonce works now, I’ll try and explain how we verify it. We can use WordPress function, wp_verify_nonce to verify that the correct nonce was used in the time limit. If that’s not true, we return the $post_id to abort the script. This stops you from being tricked into doing something you don’t want to. You can read more about nonces from Mark Jaquith.

The next snipet checks to make sure that the current user has the authority to edit a post. Because we have only created the meta_boxes on the post page, we only need to check that they can edit posts.

if ( !wp_verify_nonce( $_POST[ $key . '_wpnonce' ], plugin_basename(__FILE__) ) )
return $post_id;

if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;

If you remember the old script, in order to save the data, we first had to check to see if it existed, update it if it did, add it if it didn’t, or delete it if it was blank. Phew! A lot of checking. Imagine having the database do that 10 times? Seems quite slow right?

Well shortly after I wrote the old tutorial, WordPress updated update_post_meta so that if the row does not yet exist, it will create if for you. That allows us to only use one function, instead of checking for three. (I decided to exclude the delete, because chances are you’ll always have something, and one row isn’t nearly as bad as 3 or 4.)

So our final save function looks like this:

function save_meta_box( $post_id ) {
global $post, $meta_boxes, $key;

foreach( $meta_boxes as $meta_box ) {
$data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ];
}

if ( !wp_verify_nonce( $_POST[ $key . '_wpnonce' ], plugin_basename(__FILE__) ) )
return $post_id;

if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;

update_post_meta( $post_id, $key, $data );
}

Final Code

Here is all of the new code. The last few lines initiate the script.

<?php
$key = "key";
$meta_boxes = array(
"image" => array(
"name" => "image",
"title" => "Image",
"description" => "Using the \"<em>Add an Image</em>\" button, upload an image and paste the URL here. Images will be resized. This is the Article's main image and will automatically be sized."),
"tinyurl" => array(
"name" => "tinyurl",
"title" => "Tiny URL",
"description" => "Add a small URL of this post that will be used to track tweets, and share the post.")
);

function create_meta_box() {
global $key;

if( function_exists( 'add_meta_box' ) ) {
add_meta_box( 'new-meta-boxes', ucfirst( $key ) . ' Custom Post Options', 'display_meta_box', 'post', 'normal', 'high' );
}
}

function display_meta_box() {
global $post, $meta_boxes, $key;
?>

<div class="form-wrap">

<?php
wp_nonce_field( plugin_basename( __FILE__ ), $key . '_wpnonce', false, true );

foreach($meta_boxes as $meta_box) {
$data = get_post_meta($post->ID, $key, true);
?>

<div class="form-field form-required">
<label for="<?php echo $meta_box[ 'name' ]; ?>"><?php echo $meta_box[ 'title' ]; ?></label>
<input type="text" name="<?php echo $meta_box[ 'name' ]; ?>" value="<?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?>" />
<p><?php echo $meta_box[ 'description' ]; ?></p>
</div>

<?php } ?>

</div>
<?php
}

function save_meta_box( $post_id ) {
global $post, $meta_boxes, $key;

foreach( $meta_boxes as $meta_box ) {
$data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ];
}

if ( !wp_verify_nonce( $_POST[ $key . '_wpnonce' ], plugin_basename(__FILE__) ) )
return $post_id;

if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;

update_post_meta( $post_id, $key, $data );
}

add_action( 'admin_menu', 'create_meta_box' );
add_action( 'save_post', 'save_meta_box' );
?>

Implementation

One of the main reasons I redid the script was to have better implementation. Because all of our data is stored in one single row, we only need to call it once.

$data = get_post_meta( $post->ID, 'key', true );

Put that inside the while in the WordPress loop. Remember to change “key” to whatever value you entered in the script. That variable is now holding the array of information stored in the database. So you can simply access it like so:

<?php echo $data[ 'tinyurl' ]; ?>

Or

<?php echo $data[ 'image' ]; ?>

Like I said, not much changed on the back-end, it’s only a few lines shorter, but it should be quite a bit more efficient, as well as more expandable.

If you have any questions about the code above, or the tutorial in general, please do not hesitate to leave a comment below. I will do my best to help answer any questions that may arise.


How-To: Taking WordPress One Step Further

WordPress Logo

Creating a website is no easy task. WordPress is an easy solution for creating a Blog, but sometimes something a little more, in terms of functionality, is needed. After trying many other platforms, I have found WordPress to be the easiest to use. Because of it’s wide array of themes, great plugin system, and easy to use administration system, WordPress takes the cake. Using a Custom Write Panel, Custom Options, and manipulating the theme files, the possibilities are almost endless. In This post we have a few ways you can transform your plain WordPress powered Blog into an easy-to-manage Internet Identity.

The Layout

There are a few things that even the novice WordPress user can do. You can work straight out of your admin panel for a quick solution, or if you are feeling adventurous, editing some theme files can help produce a fresh new structure for your site.

Static Homepage

Anyone who has explored the WordPress admin panel has probably seen the options required for this, but may have not known what they do. WordPress has a built in feature which allows for the Blog owner to select a published page to show up as their default homepage, and select a separate page to list the blog posts. This is great if you want your visitors to see a static page first (ex. About Me page), before they go on and view the blog posts.

You first need to select the page which will show first. Just select any page from the drop-down list that has content on it. Next, you will need to select a blank (but published) page to show the blog posts on. Just create a page like you would normally, adding a title (ex. Blog), but no content. Select that page from second option’s drop-down

home.php

WordPress has another built in feature (it seems they love to make our lives easier) that allows for a completely custom homepage. If your homepage has a different layout from your blog, you can create a separate file, and have that loaded as your homepage. As seen in the template hierarchy, WordPress first checks to see if a home.php file exists. If so, it will load that instead of index.php.

So by creating a file named home.php, filling it with whatever you would like, and uploading it into your theme’s root folder, you are able to create a separate homepage. By utilizing the Loop, this is a great way to show only certain posts when the guest first views the site.

Note: All HTML Markup is based on the WordPress Default Theme.

<?php get_header(); ?>

<div id="content" class="narrowcolumn">

<h2>Welcome!</h2>

<p>This can be a custom part of the <code>home.php</code>, just a little custom welcome text. You can check out some of our latest <b>News Posts</b> below.</p>

This should all look pretty familiar if you have any experience working with WordPress themes. First, I’ve included the header.php file with the get_header(); function. Then just some basic HTML Markup that includes a welcome message at the top of the page.

<h2>News Posts</h2>

<ol>

<?php query_posts( 'cat=60' ); if (have_posts()) : ?>

<?php while (have_posts()) : the_post(); ?>

<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>

<?php endwhile; ?>

<?php else : ?>

<li>There are no new posts in this category.</li>

<?php endif; ?>

</ol>

Here is where we are going to list our latest Blog posts. It is just a basic loop, except for one minor difference:

<?php query_posts( 'cat=60' ); ?>

query_posts can be used to modify a WordPress loop. I’ve modified this loop to only show one category, in my case, a news category.

The last part of our home.php:

</div>

<?php include_once( TEMPLATEPATH . '/sidebar-homepage.php' ); ?>

<?php get_footer(); ?>

The last difference is the way I include a sidebar. By using an include_once(), I can include a different sidebar in our home.php. You can use a Include Tag to include a separate file. In the same directory as your theme files, create a file you would like to include in your sidebar.

Live Examples

WooThemes

Custom Page Templates

Like using a home.php, using a Custom Page Template is useful for creating unique pages that do not fall under the same layout as your main blog. However, custom Page Templates allow for any page to be custom, not just the homepage. The best part about them, is they are super easy to make.

If I wanted my “About Me” page to include a different sidebar then the rest of my blog, and perhaps the Search Form above it, there is a very easy way to go about this. In your theme’s directory, just create a file called about.php

<?php
/*
Template Name: About
*/
?>

That is the most important part. WordPress will read the top of the file and realize that this file is supposed to be used as a Page Template. Below that, you can add whatever code you like. There are two ways of doing it. You can add static content to your post, or add the Loop again, so the content is retrieved from WordPress. Here is an example of the latter:

<?php
/*
Template Name: About
*/
?>

Live Example:

Cushy by WooThemes

Conditional Tags

Let’s face it. Viewing the same style pages eventually get’s a little mundane. If you’re looking for a way to spice up your site, or just show different information on certain pages, there are a few ways to do it. Conditional Tags as well as custom pages allow for the ultimate control. Below are just a few scenarios:

If you are not currently viewing a Page, show the sidebar. If you are on a Page, do not show the sidebar.

<?php if( !is_page() ) : ?>
<?php get_sidebar(); ?>
<?php endif; ?>

If you are on the homepage, get a special footer file. If not, show the normal one. This could be used to show more information about your company or site when the visitor first views the site.

<?php if( is_home() ) : ?>
<?php include (TEMPLATEPATH . "/footer-info.php"); ?>
<?php else : ?>
<?php get_footer(); ?>
<?php endif; ?>

For a full list of Conditional Tags, check out the Codex.

The Loop

The Loop. The Loop. The infamous loop. The Loop can be a wonderful thing, or a scary one. It all depends on how you approach it. I’m going to show you a more advanced way of using a Loop, because you can find some great info on the Loop on the WordPress site.

Creating a Gallery Site

Creating a gallery can be great for a portfolio site, a “best web gallery” site, or anything that requires showing some images of stuff. :P

The code and/or information below assumes you have successfully setup Custom Write Panels

The basic structure for a gallery type site is simple. Create the post adding the necessary information, and list the posts in the gallery page. To start off, make sure you have added the following Custom Write Panels.

  • Image
  • Website

These are the only ones needed to create a simple gallery, but of course it can be easily modified to fit any of your needs. The next part would be to create the actual Gallery page. This can be done using a Custom Page template.

<?php
/*
Template Name: Gallery
*/
?>

<?php get_header(); ?>

<?php get_footer(); ?>

Now it’s time to add the loop (in between get_header(); and get_footer();) which will show our posts.

<div id="content" class="widecolumn">

<?php query_posts( 'category_name=Gallery' ); if (have_posts()) : ?>

<?php while (have_posts()) : the_post(); ?>

<?php endwhile; ?>

<?php endif; ?>

</div>

You will of course need to change category_name=Gallery to the name of your category.

For now, I’m just going to do the basic markup. No styling or anything, just so you can get how the the code will be set up. First, we’ll do our gallery item’s title like normal:

<h2><?php the_title(); ?></h2>

Now the cool part. Using a great script called TimThumb we can dynamically create thumbnails of any size. Download the source, and upload it into your theme’s folder under thumb.php

Download TimThumb

Now we’ll start a link so the thumbnail is clickable.

<a href="<?php echo get_post_meta( $post->ID, "website_value", true ); ?>" title="<?php the_title(); ?>">

I’m setting the URL to be equal to the value entered in our custom field.

Next the image: This gets the value of the image field, and applies the TimThumb code, setting the thumbnail to 100x100px.

<img src="<?php bloginfo( 'template_directory' ); ?>/thumb.php?src=<?php echo get_post_meta( $post->ID, "image_value", true ); ?>&amp;w=100&amp;amp;amp;amp;amp;h=100&amp;amp;amp;amp;amp;zc=1" alt="<?php the_title(); ?>" />

And end the link:

</a>

The last part would be to show the description of the website. We can do that by showing an excerpt of the post body.

<?php the_excerpt(); ?>

That’s it for our gallery.php. Now it’s time to activate the Gallery page. In your WordPress admin panel, go to Write > Page. Create a new page with a title of “Gallery.” Leave the body blank, and apply our Page Template

Now, create a post with the correct information, and visit your gallery page. It should list all of your information! Of course, the gallery.php is a very simple, minimalistic page; but it functions.

Note: If your thumbnails are not showing up, please make sure you created a folder named “cache” in your theme’s directory, and it is writable.

Custom Loops

Sometimes you may find yourself needing to use more then one loop. However, an important note on the WordPress codex tell us that instead of using query_posts like we did in our gallery system (it was okay there, because it was the main, and only loop, in our page), we need to use something called WP_Query();. This can be used to fetch any posts, and best of all, it uses the same parameters are query_posts.

First, we need to define a variable as a new query. Then we take that variable, and apply some parameters to it:

<?php $latest = new WP_Query(); $latest->query( 'showposts=10&amp;amp;amp;amp;amp;cat=-63' ); ?>

Next, we simply loop through the results just like we would with a normal loop.

<?php while ($latest->have_posts()) : $latest->the_post(); ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<?php endwhile; ?>

Like I said, you can use any of the Parameters, making this a great tool to grab posts from certain categories and displaying them around your site.

Social Networking

With the amount of social networking sites, topsites, and tons of ways to spread the word about your articles and blog posts, there has to be an easier way to submit them. By adding links to the bottom of your posts, you can get users to submit your articles for you!

Site RSS

<a href="<?php bloginfo('rss2_url'); ?>" title="<?php _e('Syndicate this site using RSS'); ?>"><?php _e('<abbr title="Really Simple Syndication">Subscribe</abbr>'); ?></a>

Stumble Upon

<a href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&amp;title=<?php the_title(); ?>" title="Submit to StumbleUpon">StumbleUpon</a>

Digg

<a href="http://digg.com/submit?phase=2&amp;url=<?php the_permalink() ?>&amp;title=<?php the_title(); ?>&amp;bodytext=<?php the_excerpt() ?>" title="Digg this story">Digg this</a>

Del.ic.ious

<a href="http://del.ic.ious/post?url=<?php the_permalink() ?>&amp;title=<?php the_title(); ?>" class="delicious" title="Add to Del.icio.us">Del.icio.us</a>

Design Float

<a href="http://www.designfloat.com/submit.php?url=<?php the_permalink(); ?>&amp;title=<?php the_title(); ?>">Float This</a>

Mixx

<a href="http://www.mixx.com/submit?page_url=<?php the_permalink(); ?>">Mixx</a>

Obviously there are tons more. All you have to do is figure out what variables the submit page takes to fill in the fields, and then create the URL dynamically. Here is a list of some variables you can use.

  • the_title(); – The Post Title
  • the_permalink(); – The Post’s URL
  • the_excerpt(); – A small portion of the article

Conclusion

There are a million ways you can customize and expand your WordPress powered site. I’ve touched on a few, but of course, there are many more. If you are interested in learning a different aspect of WordPress, please leave a comment and let me know. I’ll leave you know with some great WordPress powered sites, that you may or may not have known ran WordPress.

Resources
WordPress Powered Sites

CNN Blogs

Best Web Gallery

Fuel Your Creativity

Number 10.co.uk

Outlaw Design Blog


  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress