WordPress plugins, themes, tips and hacks

Archive for the ‘Code Snippets’ Category

How to create a Simple Directory in Wordpress using Grandparent, Parent, and Child Pages

Thursday, June 4th, 2009

I wanted to create a simple directory of non-profit organizations. To do so,  I wanted to use pages for the directory, rather than posts so that I could separate the static directory listings from the dynamic blog posts. I didn’t want to have to exclude tons of categories from feedburner and the main loop.

So, I started exploring the whole family in Wordpress – grandparents, parents, and children. Translation for those not yet used to seeing Wordpress analagous to the family in My Big Fat Greek Wedding: Pages, sub-pages, and sub-sub pages

Simple Directory Setup

  • Directory Page (grandparent): Displays list of Non-Profit Organization Categories (ex. social, environment, health, etc.)
  • Category Page (parent): Show title and excerpt of each Organization within a category (ex. Environment Organizations)
  • Single Organization Page (child/current): Show content about a single organization(ex. SaveTheEarth – made up org for this example)

Here’s how to do it

  1. Create a Page Called Directory. This will be the Directory Page (grandparent)
  2. Find the Page ID. Let’s say the Page ID = 5. Depending on how you want to display the category info, you can
  3. Manually add the name of each category, a short description and a link
  4. Open up page.php so we can setup The Category Page (Parent Page). We want to show title and excerpts of each organization for each category.
  5. Add this code to page.php – Checks if we’re on a sub page / child page of the Directory (Page ID =10) and if so, list the pages in alphabetical order with excerpts. For the excerpt, I’m using the plugin Limit Posts since it didn’t work with The Excerpt Reloaded.<?php
    $current = $post->ID;
    $parent = $post->post_parent;
    $grandparent_get = get_post($parent);
    $grandparent = $grandparent_get->post_parent;
    ?>

    <?php if ( $post->post_parent==”10″   ){ ?>
    <?php $pageChildren = $wpdb->get_results(”SELECT *    FROM $wpdb->posts WHERE post_parent = “.$post->ID.”    AND post_type = ‘page’ ORDER BY post_title ASC”, ‘OBJECT’);    ?>

    <h2 class=”titles”><a href=”<? php echo get_permalink($pageChild->ID);  ?>”> <? php echo $pageChild->post_title;  ?></a></h2>

    <?php the_content_limit(280, “”); ?><div class=”readmore”><a href=”<?php echo get_permalink($pageChild->ID); ?>” rel=”bookmark” title=”Permanent Link to <? php echo $pageChild->post_title;   ?>”>Read More &raquo;</a></div>

    (make sure to delete the space between <? and php -  I had to to do that so it wouldn’t execute in this post)

  6. Single Organization Page (Child Page) On page.php, after the code you added in step 5, add this code that will check to see if we’re on the grandchild page. This will be the actual organization’s page. In our example, the SaveTheEarth Page. This is very helpful information in case you want to add a different style or add special items in the sidebar, etc.
    <?php if ( $pageChildren ) : foreach ( $pageChildren as $pageChild ) : setup_postdata( $pageChild ); ?>

7. Set up how the rest of the pages on your site will look:

On page.php, after the code in step 6, add this code which instructs every other page in the site to act normally and display the content

<?php endforeach; ?>
<?php else : ?>

<?php the_content(); ?>
<?php  endif; ?>

You can see the full page.php code here

You can see the directory in action here

I figured this out using the following helpful posts:

* http://wordpress.org/support/topic/186206
* http://wpguru.co.za/page/display-title-excerpt-of-child-page

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

How to rename widgetized sidebars in Wordpress

Thursday, November 20th, 2008

You can manage multiple sidebar widgets in WordPress. To do so, you go to the Widgets page in the Admin, and select the Sidebar you want to manage. If you have 1 widgetized sidebar, the name “Sidebar 1″ is not a big deal for managing it. But what if you have 5 or more, and they’re named Sidebar 1, Sidebar 2, etc. Ah yes, now what was that wily sidebar 3 for?

Why would someone have so many sidebars to begin with? Well, remember that you can also add widget-ready sidebars to Wordpress footers or anywhere in your design, to give extra content management options to clients.

Recently, we had a client with way too many widgetized sidebars to keep track of, so we had to find a new solution to change the standard widget sidebar names like “sidebar 1″ or “sidebar 2″ to something more meaningful like “Left sidebar” and “Right sidebar” in the admin area. I dug around the web and found 2 very helpful posts:

Here’s what I learned:

1. Go into your themes’s function.php file, or if it doesn’t exist, create it.

Add the following code:

<?php

if (function_exists(’register_sidebar’))

{

register_sidebar(array(

‘before_widget’ => ‘<li>’,

‘after_widget’ => ‘</li>’,

‘before_title’ => ‘<h4>’,

‘after_title’ => ‘</h4>’,

‘name’ => ‘Left sidebar’

));

register_sidebar(array(

‘before_widget’ => ‘<li>’,

‘after_widget’ => ‘</li>’,

‘before_title’ => ‘<h4>’,

‘after_title’ => ‘</h4>’,

‘name’ => ‘Right sidebar’

));

}

?>

2a. Add a widgetized sidebar to your theme. Open up your theme’s sidebar file (for exampe, l_sidebar.php) and look for the first <ul> or <ul id=”sidebar”> or something similar, and add the following code:

<?php if ( !function_exists(’dynamic_sidebar’) || !dynamic_sidebar(’Left sidebar’) ) : ?>

2b. If your sidebar is already widgetized, find the following code

<?php if ( function_exists(’dynamic_sidebar’) && dynamic_sidebar(1) ) : else : ?>

and replace it with

<?php if ( !function_exists(’dynamic_sidebar’) || !dynamic_sidebar(’Left sidebar’) ) : ?>

Then, find the closing </ul> at the very bottom of the file, and immediately before that, place

<?php endif; ?>

3. Now, if you go into your admin panel, under Design>Widgets, you’ll see the new names like in the image below.

Now you can easily manage your Widgets without trying to guess which one is which.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Publishing WordPress posts in two columns

Thursday, March 20th, 2008

We’re currently building a site on Adii’s Premium Gazette WordPress theme (this is an affiliate link). In my opinion, it’s an awesome theme particularly because of the design. However, we installed it on the client’s server of choice, and the posts on the homepage just wouldn’t update. We tested it out on different servers, as well as on the client’s server without any plugins or changes, and it worked on other servers but would not cooperate on the client’s server.

The home page of this WordPress theme has two columns of posts. This is a really handy layout, but we realized that the code being used to create this layout was causing all the problems. So we needed to find another solution.

cre8d design has a tutorial on how to organize posts into two side-by-side columns in WordPress. It’s based on adding a “switch” that tells WordPress if a post should appear in the first column or the second column. Basically, the code is saying the following:

Are we in the first column?
Yes: Move to the second column.
No: Move to the first column.

The code calls styles from your style sheet that tell the left column to float left, and the right column to float right.

cre8d’s demo page for this technique:

Posts in two columns in WordPress

We also needed to exclude two categories from appearing on the homepage, so here’s a simplified version of the final code we used to replace Adii’s code in his default.php file:

<div class="box"><?php query_posts('showposts=4'); ?><?php $hol = 1; ?>

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

<?php if (in_category('3')) continue; ?>

<?php if (in_category('4')) continue; ?>

<?php if ($hol == 1) echo "<div class=\"row\">"; ?>

<div class="post hol<?php echo $hol;?>" id="post-<?

php the_ID(); ?>">

<?php if ( get_post_meta($post->ID, 'thumb', true) )

{ ?> <!-- DISPLAYS THE IMAGE URL SPECIFIED

IN THE CUSTOM FIELD -->

<img src="<?php echo get_post_meta($post->ID, "thumb",

$single = true); ?>" alt="" />

<?php } else { ?> <!-- DISPLAY THE DEFAULT IMAGE, IF CUSTOM

FIELD HAS NOT BEEN COMPLETED -->

<img src="<?php bloginfo('template_directory'); ?>

/images/no-img-thumb.jpg" alt="" />

<?php } ?>

<h2><a title="Permanent Link to <?php the_title(); ?>"

href="<?php the_permalink() ?>" rel="bookmark">
<?php the_title(); ?></a></h2><p><?php the_excerpt(); ?></p>

<?php if ($hol == 1) echo "</div>";

(($hol==1) ? $hol=2 : $hol=1); ?>

</div><!--/post-->

<?php endwhile; ?>

<?php endif; ?>

The following styles need to be added to your style sheet so that the columns float left and right:

.row { clear: both; }
.hol1 { width: 200px; float: left; padding: 0 10px; }
.hol2 { width: 200px; float: right; padding: 0 10px; }

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Faviconize your WordPress admin

Sunday, January 6th, 2008

The WordPress admin doesn’t have a favicon. That means that when you’re working with a bunch of tabs open, it’s hard to identify which one is for your WordPress admin. Well, Simply Basic has the solution – simply add one line to wp-admin/admin-header.php that calls the favicon of your choice:

<link rel="shortcut icon" href="<?php bloginfo('url'); ?>/favicon.ico" >

The only drawback is that you have to remember to redo this change every time you upgrade. It might be helpful if there was a plugin that did this for you (hint, hint).

Simply-Basic.com » Give WP-Admin a Custom Favicon

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Using PHP to alternate background colors for comments or posts in WordPress

Wednesday, December 26th, 2007

Some blogs have alternating background colors for their comments and posts, i.e. a green background for every even comment and post, and a grey background for every odd comment and post. How do they do that?

Alternating Comments Styles

To alternate comments, add the following code to your comments.php template file, under where it says <?php if ( $comments ) : ?>:

<ul>
<?php $i = 0; ?>
<?php foreach ($comments as $comment) : ?>
<?php $i++; ?>
<li id="comment-<?php comment_ID() ?>"<?php if($i&1) { echo 'class="odd"';} else {echo 'class="even"';} ?>>

Then, create a style called .even and a style called .odd in your style.css file. Give each style a different background color, like this (but change the colors to what you want):

.odd {
background-color: #fcf9fc; }

.even {
background-color: #616161; }

This information is from the following WordPress support topic:

How to alternate background colors of comments posted on blog?

Alternating Post Styles

Adam Brown has a tutorial on his site for creating alternating styles for posts. Basically, you do the following:

  1. Right before the loop begins, add the following code:
    <?php $odd_or_even = 'odd'; ?>
  2. Right after the loop, there will be a div. Let’s say it’s called class=”post”. Change it to
    <div class="post <?php echo $odd_or_even; ?>">, and then add the following piece of code on the next line: <?php $odd_or_even = ('odd'==$odd_or_even) ? 'even' : 'odd'; ?>
  3. Now, create .odd and .even styles in your style.css.

Adam’s site has another really useful PHP Tutorial for Wordpress Users, which is good for those of us who aren’t going to become PHP gurus, but would like to know enough PHP to extend our WordPress sites.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Giving each comment its own link in WordPress

Wednesday, November 28th, 2007

Being able to link to specific comments in your WordPress blog could be very handy. Good comments can really add a lot of value to a blog, and you or others may want to refer to specific comments in your posts by linking to them. In general, comments can be linked to, but to figure out what the URL is for every comment is virtually impossible, unless…you set up your comments section of your blog so that every comment gets a link.

Here’s how you would create a link around the date and time of your comment:

<p><a href="#comment-<?php comment_ID() ?>" title=""><?php comment_date('F jS, Y') ?> at <?php comment_time() ?></a></p>

This piece of code should appear in your comments.php theme file where your comment code appears.

If you want an “Edit Comment” link to appear next to the comment for those who are logged in and have permissions to edit, you would add the following code:

<p><a href="#comment-<?php comment_ID() ?>" title=""><?php comment_date('F jS, Y') ?> at <?php comment_time() ?></a><?php edit_comment_link('Edit comment',' ~ ',''); ?></p>

So there you have it boys and girls: now you can link to comments, and share the love with your commenters!

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Giving each WordPress post a thumbnail, and display the thumbnail on the home page

Wednesday, November 21st, 2007

You may encounter situations where you need to automatically display a thumbnail or image of some kind that will link to posts. Here’s an example of this kind of situation: you want to display recent posts from a certain category on your home page, with a thumbnail for each post and maybe the title and an excerpt. Or, I recently had a client that had a box on their homepage for multimedia where they wanted an image to appear that would represent the latest post in the Media category and would link to that post. A link to this site is at the end of this post, so read on.

I found the solution in two amazing WordPress themes: Mimbo and The Morning After. They both use thumbnails on their home page, and they do it by using WordPress’ mysterious Custom Fields feature.

You need to be able to upload images to your server in order to do this. You can do this via FTP, but to make this as easy as possible for clients, I use the Filosofo Old-Style Upload Plugin which creates a link on your nav bar where you select files for uploading. But first you need to configure this plugin and select a folder where all uploads will be saved:

  1. Upload the plugin and activate it.
  2. Go to Options > Uploads.
  3. Enter your destination directory. I think the best is to use your images folder in your theme folder so that any images you upload will be in an easily portable place. So the path could be something like /home/server/public_html/wp-content/themes/themefolder/images. The plugin will suggest a path, and it is usually right.
  4. Enter the URI of the folder. It’s something like http://www.yoursite.com/wp-content/themes/themefolder/images.
  5. You might as well up your maximum file size. I make it 500 kb.
  6. Allowed file extensions: jpg, jpeg, gif, png, pdf – I add PDF and other types of files I think clients may want to upload.
  7. Minimum level to upload: I leave it at 6 since I have no idea what this means.
  8. Click Update Options.

That’s done. Now for how to create a post with a thumbnail image.

  1. Create an image for your post with the right width and height. The size of the image depends only on the design of your site and where it is going to appear.
  2. Go into the admin of your site. Click on Upload (it’s on the upper nav bar).
  3. Select the file you are uploading, select No Thanks so it won’t create a thumbnail, give it a description (that’s good for Google) and click Upload File.
  4. Once it’s uploaded it will show you the entire URL of the image. Note particularly the last part of the link where it says the name of your image, especially if there are any capitals in any part of the name. You will have to enter the exact file name in step 8.
  5. Go to Create Posts. Enter your post and title as you wish. Make sure to select the category you have selected as the one that will appear with the thumbnails. Now scroll all the way down to the bottom of the screen where it says Custom Fields. Click on the plus button to expand it.
  6. Enter the word Image (with a capital I) in the Key field.
  7. In value, enter the exact name of the file you uploaded. For example picture.jpg or image.gif. Click Add Custom Field.
  8. Save your post.

Now we need the code that will make this thumbnail appear where you want it to appear. Following is the code for having a thumbnail appear with the title underneath it. This code is adapted from the Mimbo theme, but the code in The Morning After is similar:

<?php
// this is where the Features module begins
query_posts('showposts=1&cat=199'); ?> //change the showposts number to the number of posts that you want to appear, and change cat=199 to your category number, which you can find out by going to Manage > Categories
<?php while (have_posts()) : the_post(); ?>
<div class="thumbnails"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><img src="<?php echo get_option('home'); ?>/wp-content/themes/themefolder/images/<?php
// this is where the custom field prints images for each Feature
$values = get_post_custom_values("Image"); echo $values[0]; ?>" alt="" /></a>
<p class="title"><a href="<?php the_permalink() ?>" rel="bookmark">
<?php
// this is where title of the Feature gets printed
the_title(); ?></a></p></div>
<?php endwhile; ?>

Wanna see an example? Check out this site, scroll to the bottom and look at the left-most column that is called Media. That image there is a thumbnail that was uploaded and entered in the Custom Field of the post it links to.

Update Nov. 27, 2007: This post got a lot of comments here, and on Weblog Tools Collection who referred to it. Lots of people gave more recommendations on how to manage thumbnails with custom fields and/or plugins, so I collected these tips into one post which you can see here: Images, thumbnails and custom fields in WordPress.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Hard-coding an SEO friendly title in the WordPress header file

Monday, November 12th, 2007

The title I am referring to here is the title that appears in the top bar of your browser, and is in betweeen <title></title> tags in your code. Apparently, to make it more SEO friendly, the title of the post or article should appear before the title of your blog, but generally themes have it programmed the other way around.

You can switch it through the use of plugins, but if you want to avoid using another plugin you can fix this in the header.php file. Find the code that starts with <title>, and replace what is currently there with this:

<title><?php if ( is_single() ) { ?> <?php wp_title(''); ?> &raquo; <?php } ?><?php bloginfo('name'); ?></title>

This tells WordPress that if the page is not single, the name of the blog will appear only. This is for the homepage. If the page is single, i.e. a single post page, then the name of the post will appear and then the blog title. So, for example, a post on WordPressGarage would have the following title:

Yet another way to feed your facebook obsession » WordPressGarage

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Display recent posts in WordPress sidebar

Sunday, November 11th, 2007

Here’s a bit of code to put in your sidebar to display the most recent posts on your blog:

<?php $myposts = get_posts('numberposts=10&offset=1');
foreach($myposts as $post) :? >
<li><a href="<?php the_permalink(); ?>"><?php the_title();?></a></li>
<?php endforeach; ?>

You can set the number of recent posts to appear on the first line of code where it says numberposts=10 – change the 10 to the number of posts you want to appear. You can choose to offset the recent posts by any number; for example, if you select offset=1, as we did above, it won’t display the most recent post, but will start the list from the second-most recent post.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Recent Comments code snippet

Friday, November 9th, 2007

This code is from the Blog Oh Blog theme, and displays recent comments in the sidebar without the need for a plugin:

<?php
global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID,
comment_post_ID, comment_author, comment_date_gmt, comment_approved,
comment_type,comment_author_url,
SUBSTRING(comment_content,1,30) AS com_excerpt
FROM $wpdb->comments
LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID =
$wpdb->posts.ID)
WHERE comment_approved = '1' AND comment_type = '' AND
post_password = ''
ORDER BY comment_date_gmt DESC
LIMIT 10";
$comments = $wpdb->get_results($sql);
$output = $pre_HTML;
$output .= "\n<ul>";
foreach ($comments as $comment) {
$output .= "\n<li>".strip_tags($comment->comment_author)
.":" . "<a href=\"" . get_permalink($comment->ID) .
"#comment-" . $comment->comment_ID . "\" title=\"on " .
$comment->post_title . "\">" . strip_tags($comment->com_excerpt)
."</a></li>";
}
$output .= "\n</ul>";
$output .= $post_HTML;
echo $output;?>

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]
Premium News Themes