Archive for the ‘Code Snippets’ Category

How to get around WordPress’ limitation on uploading certain file types

Tuesday, March 16th, 2010

One of our clients needed to upload files via their admin, and kept getting the following error message: “File type does not meet security guidelines. Try another.”

This was something new to us, and after doing some research we discovered that WordPress only allows users to upload certain types of files, and any files that are not part of that list cannot be uploaded through the admin. Here’s the list of accepted WordPress files types.

It turns out that the list of accepted file types is found in wp-includes/functions.php. Since we don’t want to modify WordPress core files, we need a solution like a plugin in order to get around this limitation.

Chris Meller has a solution that involves adding some code to your functions.php file in your theme directory. He also explains how to remove file types from the list of allowed files types.

For more info on how to do this, see this post on his blog: Modifying Allowed Upload Types in Wordpress.

Thanks to Mark Kaplun for helping us find this solution.

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

Display sticky post and exclude it from recent posts list in WordPress

Monday, January 11th, 2010

We were working on a WordPress site that needed to display a sticky post at the top of the blog page with one style, and then below it a list of the most recent posts with a completely different style.

I realize that you can just style the sticky post using the sticky-related classes provided by WordPress:

<div <?php post_class(); ?>> and .sticky class

but I needed to have design elements appear in between the sticky post and the rest of the recent posts, and the recent posts needed to have a completely different design than the sticky. Therefore I decided to go with a 2 loop solution. Once we were using two loops, we had to also make sure that sticky post did not repeat itself and appear in the list of recent posts following it.

Nathan Rice provides a lot of useful information about sticky posts but I couldn’t get the code he posted to work properly. So I went on a hunt to figure it out.

How to display a sticky post

The best solution I found for how to display a WordPress sticky post was a comment by Eduardo on Justin Tadlock’s post Get the Latest Sticky Post. He gave the following code:

<?php
$sticky = get_option( ’sticky_posts’ );
query_posts( array( ‘post__in’ => $sticky, ‘caller_get_posts’ => 1, ‘orderby’ => ID, ’showposts’ => 2 ) );
?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<a href=”<?php the_permalink(); ?>” rel=”bookmark” title=”Permanent Link to <?php the_title(); ?>”>
<?php endwhile;?>

<?php endif; ?>

It worked very nicely.

How to exclude sticky posts from a list of recent posts

I then wanted to show a list of 3 recent posts that excluded the post that had been defined as sticky. After many trials and errors with different solutions posted around the web, I finally found one that worked on the WordPress Support Forum.

<?php $sticky = get_option(’sticky_posts’) ;

$post_to_exclude[] = $sticky[0];

$args=array(
‘caller_get_posts’=>1,
’showposts’=>2,
‘post__not_in’=> $post_to_exclude,
);

query_posts($args); ?>

<h2><a href=”<?php the_permalink() ?>”><?php the_title(); ?></a> </h2>

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

<?php endwhile;?>

So there you have it: a workable way to have a WordPress sticky post with one style, and a list of recent posts excluding the sticky post with a completely different style below the sticky post.

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

How to list the 4 latest posts with only one post per author in WordPress

Monday, September 14th, 2009

Recently, one site we were working on needed a sidebar that would show the 4 most recent posts on the site. But here’s the catch: they wanted only one post per author. And, each author had to have the role of “author” as opposed to contributor or admin.

The site in question is still in Beta, so I can’t give out the link yet. But here’s a snapshot to give you a better idea of what we were going for.

wpgblogs

We also used the plugin User Photo to show each author’s thumbnail, which I have come to love and recommend.

Thanks to Mark Kaplun for this great solution:

Open your Sidebar.php file and add the following:

Please note: this code uses the plugin Limit Posts to create excerpts. But you can substitute that snippet with any type of excerpt code.

<?php $authors = get_users_of_blog(); ?>

<?php
$latest_posts = array();
foreach ( $authors as $author ) {
$user = new WP_User( $author->ID );
if ($user->has_cap(‘level_7′))
continue;
$ps = get_posts(‘numberposts=1&post_type=post&author=’ . $author->ID . ‘&cat=-9,-3′);
foreach ($ps as $p) {
$latest_posts[$p->post_date] = $p;
}
}
krsort($latest_posts);
?>
<?php //query_posts(‘author=’ . $author->ID . ‘&showposts=1&cat=-9,-3′); ?>
<?php
$counter =0;
foreach ($latest_posts as $post) {
$counter++;
if ($counter > 4)
break;
setup_postdata($post);
?>

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

<li>
<?php userphoto_the_author_thumbnail(); ?>
<span class=”blogauthor”> <?php the_author_posts_link(); ?> </span>
<div class=”blog”>    <a title=”Permanent Link to <?php the_title(); ?>” href=”<?php the_permalink() ?>” rel=”bookmark”><?php the_title(); ?></a></div>
<br />

<?php  the_content_limit(‘55,read more’); ?> <strong><a title=”Permanent Link to <?php the_title(); ?>” href=”<?php the_permalink() ?>”>Read more</a>   </strong>
</li>
<?php } ?>

<?php // }; ?>

The End. Yay code!

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

How to Customize Multiple Search Result Pages in Wordpress

Thursday, July 23rd, 2009

In the previous post, we discussed how to hack the search function in Wordpress to have an additional search form that would search  subcategories. Now that you have 2 or more search forms on your site, you might need to customize the search results. Thanks to this solution, I learned how to create multiple search result pages.

Let’s say we have 2 search forms on our site:

  1. General Site-Wide Search
  2. Recipe Search – searches subcategories of the Recipe Category

The first thing we need to do is tweak the search.php template to use it as a filter that will recognize if a search is coming from the Site-Wide search form or the Recipe Search form.

1. Open Search.php and delete everything.  Add the following code:

<?php
/* Template Name: Search Results */
$search_refer = $_GET["site_section"];
if ($search_refer == ‘recipe’) { load_template(TEMPLATEPATH . ‘/recipe-search.php’); }
elseif ($search_refer == ’site-search’) { load_template(TEMPLATEPATH . ‘/site-search.php’); }; ?>

2. Open Header.php or wherever the General Site-Wide Search Form is located and add this line:

<input type=”hidden” name=”site_section” value=”site-search” />

The Site-Wide Search form will look something like this:

<form method=”get” id=”searchform” action=”<?php bloginfo(‘home’); ?>/”>
<div id=”search”>
<input type=”text” value=” ” onclick=”this.value=”;” name=”s” id=”s” />
<input type=”hidden” name=”site_section” value=”site-search” />

<input name=”" type=”image” src=”<?php bloginfo(’stylesheet_directory’); ?>/styles/<?php echo “$style_path”; ?>/search.gif” value=”Go” />
</div><!–/search –>
</form>

3. Open Recipes.php or wherever your second search is and insert this line:

<input type=”hidden” name=”site_section” value=”recipe” />

You can change the value “recipe” to whatever suits your needs. Just make sure it matches the value in search.php.

The Recipe Search form for your second search will look something like this. In my case, this second search is meant to search the subcategories of the Recipe category.  See my previous post to learn about hacking the search function to search subcategories.

<form method=”get” id=”rsearchform” action=”<?php bloginfo(‘home’); ?>/”>
<div id=”rsearch”>
<input type=”text” value=”Recipe Search… ” onclick=”this.value=”;” name=”s” id=”rs” />
<?php $categories = get_categories(‘child_of=11′);
$catlist = ”;
foreach ($categories as $cat) {
$catlist.= $cat->cat_ID.’,';
}
$catlist.’11′;
?>
<input type=”hidden” name=”cat” value=”<?php echo “$catlist”?>” />
<input type=”hidden” name=”site_section” value=”recipe” />
<input name=”" type=”image” src=”<?php bloginfo(’stylesheet_directory’); ?>/styles/<?php echo “$style_path”; ?>/search.gif” value=”Go” />
</div><!–/search –>
</form>

4. Customize the Search Results Templates

If you recall, in step 1, we added the following to the search.php page.

if ($search_refer == ‘recipe’) { load_template(TEMPLATEPATH . ‘/recipe-search.php’); }
elseif ($search_refer == ’site-search’) { load_template(TEMPLATEPATH . ‘/site-search.php’); }; ?>

Create recipe-search.php (or whatever you named this template) and customize the layout of the results page to your liking. You can use index.php to start with and customize from there.

Create site-search.php (or whatever you named this template) and customize the layout of the results page to your liking. You can use index.php to start with and customize from there.

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

How to Hack the Wordpress Search Function: Search Categories and Child Categories

Tuesday, July 21st, 2009

Recently, we had a client who wanted a special recipe search. There were 2 ways to extend the search functionality – manually or dynamically.

1. Search One or More Categories Manually

If we want to search one category, we could have used this solution which lets you manually add category numbers to the search function:

[Replace value="5" with your category number.]

<form method=”get” id=”searchform” action=”<?php bloginfo(‘home’); ?>/”>
<div>
<input type=”text” value=”<?php echo wp_specialchars($s, 1); ?>” name=”s” id=”s” />
<input type=”hidden” name=”cat” value=”5″ />
<input type=”submit” id=”searchsubmit” value=”Search” />
</div>
</form>

2. Search Subcategories Dynamically

However, we wanted to dynamically search only the subcategories of the Recipe Category. The reason being that if you’re already in the Recipes section of the site, seeing a recipe labeled as Recipes is not helpful. However, seeing a recipe labeled as Dessert (mmm..) and Breakfast is helpful. So, each recipe that the client adds will be in a subcategory of recipes (ex. Dessert), but they won’t have to check off the checkbox next to the Recipes category itself.

Anyway, I’ve been looking for this solution for a long time and now, thanks to Ilan Cohen, I present it to you.

[Replace the number 5 with the parent category.]

<form method=”get” id=”searchform” action=”<?php bloginfo(‘home’); ?>/”>
<div id=”search”>
<input type=”text” value=”Search… ” onclick=”this.value=”;” name=”s” id=”s” />
<?php $categories = get_categories(‘child_of=5′);
$catlist = ”;
foreach ($categories as $cat) {
$catlist.= $cat->cat_ID.’,';
}
$catlist.’5′;
?>
<input type=”hidden” name=”cat” value=”<?php echo “$catlist”?>” />
<input name=”" type=”image” src=”<?php bloginfo(’stylesheet_directory’); ?>/styles/<?php echo “$style_path”; ?>/search.gif” value=”Go” class=”btn” />
</div><!–/search –>
</form>

The code searches through all the child categories of Category 5 (Recipes). Then, you’ll see we added an additional “5″ in this line: $catlist.’5′; just in case the client puts a recipe in the Recipes category, and not one of its subcategories.

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

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]
Premium News Themes