How To: Display WordPress Categories without Children

About a week ago I decided I was unhappy with the archives plugin I was using to display our archives, so I decided to build a custom archives page.   This archives page is fairly basic in that it displays the categories and archives side-by-side, then all the posts below it.   This way people can use Ctrl+F to quickly find posts they are looking for. 

After getting the page built, I realized all of the “child” categories I use for the WordPress Hacks theme was causing some problems, so I decided to remove them from the display.   After all, these posts can also be found in their parent category. 

If you are displaying your categories somewhere and would like to remove the children, here is the code you’ll need (for WordPress 2.5+):

<?php wp_list_categories('title_li=&depth=1&show_count=1') ?>

The depth=1 is the important one for the purpose of this hack as it is what tells WordPress not to display more than your parent categories.   By default, it is of course set to depth=0 (shows all categories).   If you are wondering what other options you have, here is what the WordPress Codex lists for the depth parameter:

  • 0 – All Categories and child Categories (Default).
  • -1 – All Categories displayed in flat (no indent) form (overrides hierarchical).
  • 1 – Show only top level Categories.
  • n – Value of n (some number) specifies the depth (or level) to descend in displaying Categories.
  • Leave a Comment
  • How To: Do a Trademark Search

    Last month when we switched from to, I mentioned that one part of the move was due to the trademark violation in the old domain name (WordPress is a trademarked term).

    Looking back, I really wish I would have known about the trademark prior to launching the blog. Moving your blog to a new domain name can be a huge hassle (I explained what was involved here) and your blog will usually take a huge hit in the search engine rankings (either temporarily or permanently). This is because most of those backlinks accrued over the past year are pointing towards the old domain name, etc.

    Being someone who manages quite a large sized domain portfolio (300+ domains), I’ve spent a lot of time over the past year or so learning how to do a trademark search when researching what domains to invest my money in and which domains I want to develop into web properties. There seems to be a good amount of interest from others wanting to know how to do this, so hopefully this post will fill that need.

    Why Should I Worry About Trademark Violations?

    Before I explain how to do a trademark search, I wanted to quickly discuss why avoiding trademark violations is so important. A trademark is filed by a company to protect their brand.

    How many of you call tissues “Kleenex”? Kleenex describes one brand of tissues, but because they did not protect their trademark, the term Kleenex has instead become a generic term for tissues.  This of course caused them to lose any control they might have had over how their name is used.

    Like any good company would, Automattic wants to protect the term “WordPress” from becoming a generic term. This is why they do not allow others to use the term “WordPress” in their domain name. This can lead to confusion with readers who believe that the domain is an official WordPress site or affiliated in some way with WordPress, which could eventually lead to problems for WordPress users (if the content is bad, incorrect, or the site is malicious in some way).

    Because of this, most trademark holders will go a long way to protect their brand, including filing lawsuits.   Lawsuits, or threatening lawsuits, has become very common with people registering names like,, etc. In order to avoid complications, avoid being forced to pull down a website/blog, or having to move your site to a new domain, you’ll want to first make sure that your potential domain/website is free of any trademarks.

    Note:  If you register a domain prior to a trademark being filed by a company, that company usually won’t have rights to take the domain from you UNLESS you are displaying ads on the site or somehow making money off their brand.  Keep this in mind if you own a domain and an upstart grows popular fast.

    How To Do a Trademark Search

    Okay, so now you know why doing a trademark search is so important.   Here are the 5 steps you need to follow to do a trademark search:

    1. Visit the US government’s sitesearch page.
    2. Click Search at the top of the right sidebar menu.
    3. Click New User Form Search (Basic).
    4. In the Search Term field, you’ll want to enter the keyword you want to check on the trademark of.
    5. Click Submit Query.

    When doing your search, you’ll want to make sure to search for your term with and without spaces. An example would be if you were looking for Burger King, you would try both “burgerking” and “burger king”.

    If you follow the above steps and search for the term “wordpress” you’ll see that it is indeed trademarked, but you can use this method to search for just any keyword you want to. I recommend doing this prior to ever launching a website of any kind, just to make sure. I also used this process after picking my business name to ensure that I wouldn’t run the risk of losing my business identity at some point down the road.

    Are you always doing a trademark search prior to launching a new website or blog?

  • Leave a Comment
  • How To: Adding a “Tweet This” Button to Your WordPress Theme

    Are you following the WordPress Recipes blog?    If not, you really should be! My fellow blogger and friend Jean-Baptiste Jung has created this blog to feature a number of “recipes” or code snippets. In addition to the content, he’s also got a great design that has been getting attention all throughout the blogosphere.

    In his latest recipe, Jean explains how to add a “Send to Twitter” link to your blog, or what I prefer to call it, a “Tweet This!” link.   The idea is to add a link on your blog (usually below the content) that people can simply click to discuss the post on Twitter.

    If you’d like to add a “Tweet This!” link to your blog, here is the code you’ll need:

    <a href=" reading <?php the_permalink(); ?>" title="Click to send this page to Twitter!" target="_blank">Tweet This!</a>

    I would think that this could potentially be another great way to fetch traffic, possibly even better than a “Digg This!” link or something else along those lines.

  • Leave a Comment
  • Fixing the Unresponsive Script Problem in WordPress 2.5+

    Yesterday in my post about moving your blog to a new domain, I mentioned that there is a problem that presents itself when posts are imported into WordPress 2.5 or later.   A quick search determined that I wasn’t the only one having this problem, so I decided to document how to fix this problem here (or at least how I was able to fix it).

    Here are the steps I took to fix the problem with the unresponsive script in the Write panel (requires CPanel/PHPMyAdmin access):

    1. Please make a backup of your database in case you run into any problems.  These are the steps that worked for me to fix the problem, but I can’t guarantee they will work for everyone. 
    2. Login in to your CPanel.   This is usually found at and usually uses your FTP password.
    3. Access your PHPMyAdmin (in CPanel this is usually found at the bottom of the MySQL Databases page).
    4. Click on the MySQL database you created for your new WordPress installation in the menu on the left.
    5. Click on wp_postmeta in the list of tables on the left.
    6. Click the Browse icon.
    7. Click on the post_id tab once to sort the list from 0 to higher.
    8. Now you’ll need to delete anything with a post_id of 0.  Depending on how many posts were imported, there may be a lot of zeroes.  I had about 600 of them to delete.

    The best way to do this is to locate the boxes with “row(s) starting from record #” between them.  In the front box put 100 (or whatever number of your choice) and always put 1 in the right box.   Click Show.  You can use the select all button and verify all of them are zero.   Uncheck any that aren’t zero and click Delete.  Repeat until all zeroes are gone.

    Now open your Write panel in your new blog’s dashboard and everything should be good!

  • Leave a Comment
  • How To: Move Your WordPress Blog to a New Domain

    Last Friday I announced that our site has moved from Hack to where we are now, at Towards the end of the post we got a lot of positive feedback from people wanting to know what all was involved with the process, so I’ve decided to attempt to document it here.

    Here are the initial steps you’ll want to take when moving to a new domain name.

    Existing Domain:

    • Export Your WordPress Posts – You can find the Export option under the Manage tab in your WordPress dashboard. You’ll want to save the file somewhere on your hard drive where you can find it a little later.
    • Download Your wp-content Folder – This step requires FTP access.  You’ll want to copy over your wp-content folder on to your hard drive or place it somewhere you can find it later so that you can upload it to your new domain. This should grab all of your existing plugins, themes, uploads (pictures), etc.   You’ll also want to download your favicon and Robots.txt file (if you have either).
    • Sub Domains and Sub Directories – This won’t apply to everyone, but if you’ve set up any sub domains or sub directories for your blog, you’ll want to grab the same files from them as well.

    New Domain:

    • Install WordPress on the New Domain – This can be done manually or via Fantastico if you have CPanel.
    • Upload Your wp-content Folder – This requires FTP access to complete.  Just override the existing wp-content folder from your fresh WordPress install.
    • Import All WordPress Posts – You can find the Import option under the Manage tab in your WordPress dashboard.  When it asks for the import file, use the one that was exported and saved on your hard drive earlier.
    • Activate Your Theme & Plugins – Head into the Design and Plugins tabs and make sure you have the same theme and same plugins activated as the old domain name.
    • Update Your Settings to Match the Old Domain – Update all of your settings to match the old domain, including all of your plugin settings you just activated.
    • Inspect Your Theme – View your theme with your plugins activated and settings in place to ensure that everything looks like it matches the old site on the new domain.  Test some of the functionality as well to ensure everything is working properly.
    • Upload and Run the Update URL’s Plugin – The Update URL’s WordPress plugin is brand new (just came out this month) WordPress plugin and the timing couldn’t have been more perfect for me!  Once activated, simply enter your old domain URL and the new one.  It will go through all of your old posts and update the domain part of the URL with the new one, and it only takes a matter of seconds.  Note:  I won’t update anchor text, only the domain in the URL.
    • Repeat Steps for Sub Domains and Sub Directories – Upload and setup your sub domains and sub directories using the same steps above.

    Domain Move Troubleshooting:

    • For some reason, since WordPress 2.5, the export/import feature of WordPress works great but sometimes causes problems with an unresponsive script error whenever you access the Write panel. I will be publishing a post tomorrow that explains how to fix this error, so make sure you are subscribed to our feed.

    Once the move is completed and everything seems to be working well, here is a mini checklist of extra things to do before making the move official:

    • Update Your Feedburner Feed – You need to edit your feed details in your Feedburner account with the new domain’s source feed
    • Update Your Email Address – This one is optional.  Setup an email account on your new domain name (for example, I setup Kyle AT WPHacks DOT com for the new site).  I recommend using Google Apps which makes it really easy and lets you take advantage of the Gmail spam guards that Google has in place (plus all of the other Gmail features).
    • Update Your Gravatar – This one is optional as well.  Log in to your Gravatar account and add the new email address you just setup.
    • Update Your PPC Campaigns – If you purchase PPC advertising with AdWords, Yahoo, or whoever, you’ll want to update the destination URLs.

    Once you’re done, all that is left is to go to your domain registrar and forward the old domain to the new domain (also known as a 301 redirect). Depending on your registrar, this is usually really easy and self-explanatory.  I would also wait 6-12 hours to make an announcement on the new domain name so that the DNS can resolve at the new domain name (it can sometimes take up to 48 hours). Depending on your web hosting, you may also be able to do the forward there to avoid this problem.

    Doing this will cause all links to your old domain name to be redirected to the equivalent URL on the new domain name (assuming you use the same URL structure on the new site). It will also let Google and the other search engines know you have moved. Usually within a week, depending on the search engine, they will have gone through and updated their index with the new domain URL’s.

    This of course means that you shouldn’t use any human traffic, but you will take a hit when it comes to your search engine rankings. This is because the links are pointed towards the old domain name, so when Google determines your rankings, they will see the new URL has zero backlinks. This is why it is beneficial if you can get people to update the links in their sidebars or posts to the new domain URL.

    Any questions?  Need clarification on anything?  Please let me know in the comments below!

  • Leave a Comment
  • How To: Build a Categories and Archives Drop-down Box

    Over the past couple years I’ve really enjoyed monitoring trends in the blogosphere and one of the trends that has come up recently is blogger’s cleaning up their sidebars by adding drop-down boxes.

    If you’d like to build drop-down boxes for your categories and archives on your WordPress blog, here is the code you need:

    Archives Drop-down Code

    <select name="archive-dropdown" onChange='document.location.href=this.options[this.selectedIndex].value;'>
    <option value=""><?php echo attribute_escape(__('Select Month')); ?></option>
    <?php wp_get_archives('type=monthly&format=option&show_post_count=1'); ?> </select>

    Categories Drop-down Code

    <form action="<?php bloginfo('url'); ?>/" method="get">
    $select = wp_dropdown_categories('show_option_none=Select category&show_count=1&orderby=name&echo=0');
    $select = preg_replace("#<select([^>]*)>#", "<select$1 onchange='return this.form.submit()'>", $select); echo $select; ?>
    <noscript><input type="submit" value="View" /></noscript>

    I think something like this can be a good idea if done with the right theme, but I have also seen it on a few sites where it didn’t look very good, so keep that in mind if you decide to move your categories and archives to a drop-down box!

    To see other code snippets we’ve featured here over the past year, check out our WordPress Code page!

  • Leave a Comment
  • How to: Display your WordPress Tags in a Drop-Down Menu

    Tags are useful to any blog: As you know it, they allow the user to display a list of posts related to a subject.
    Most of the time, tags are displayed with in a tag cloud. If you have 20 different tags, that’s ok, but if you have 100 or more tags your tag cloud will be very hard to read, and no-one will click on it.

    This is probably why many blogs recently stopped displaying their tag cloud, or put it on a separate page. But I got another solution.

    My wife owns a blog where she reviews books. She use tags to display author names, which is a great use of tags, in my opinion. The tags were first displayed as a list, and it was perfect. But after she reviewed 60+ books, the list started to be too long.

    She asked me about a solution, and after some reflection, I came up with the idea of using a drop-down menu (select html element + a bit of javascript). Happily, I was able to found this code on WordPress forums.

    First, we have to create a php function. Copy and paste the following code in the functions.php file of your theme (Be careful with the php opening/closing tags!)

    function dropdown_tag_cloud( $args = '' ) {
    	$defaults = array(
    		'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45,
    		'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC',
    		'exclude' => '', 'include' => ''
    	$args = wp_parse_args( $args, $defaults );
    	$tags = get_tags( array_merge($args, array('orderby' => 'count', 'order' => 'DESC')) ); // Always query top tags
    	if ( empty($tags) )
    	$return = dropdown_generate_tag_cloud( $tags, $args ); // Here's where those top tags get sorted according to $args
    	if ( is_wp_error( $return ) )
    		return false;
    		echo apply_filters( 'dropdown_tag_cloud', $return, $args );
    function dropdown_generate_tag_cloud( $tags, $args = '' ) {
    	global $wp_rewrite;
    	$defaults = array(
    		'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45,
    		'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC'
    	$args = wp_parse_args( $args, $defaults );
    	if ( !$tags )
    	$counts = $tag_links = array();
    	foreach ( (array) $tags as $tag ) {
    		$counts[$tag->name] = $tag->count;
    		$tag_links[$tag->name] = get_tag_link( $tag->term_id );
    		if ( is_wp_error( $tag_links[$tag->name] ) )
    			return $tag_links[$tag->name];
    		$tag_ids[$tag->name] = $tag->term_id;
    	$min_count = min($counts);
    	$spread = max($counts) - $min_count;
    	if ( $spread <= 0 )
    		$spread = 1;
    	$font_spread = $largest - $smallest;
    	if ( $font_spread <= 0 )
    		$font_spread = 1;
    	$font_step = $font_spread / $spread;
    	// SQL cannot save you; this is a second (potentially different) sort on a subset of data.
    	if ( 'name' == $orderby )
    		uksort($counts, 'strnatcasecmp');
    	if ( 'DESC' == $order )
    		$counts = array_reverse( $counts, true );
    	$a = array();
    	$rel = ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) ? ' rel="tag"' : '';
    	foreach ( $counts as $tag => $count ) {
    		$tag_id = $tag_ids[$tag];
    		$tag_link = clean_url($tag_links[$tag]);
    		$tag = str_replace(' ', '&nbsp;', wp_specialchars( $tag ));
    		$a[] = "t<option value='$tag_link'>$tag ($count)</option>";
    	switch ( $format ) :
    	case 'array' :
    		$return =& $a;
    	case 'list' :
    		$return = "<ul class='wp-tag-cloud'>nt<li>";
    		$return .= join("</li>nt<li>", $a);
    		$return .= "</li>n</ul>n";
    	default :
    		$return = join("n", $a);
    	return apply_filters( 'dropdown_generate_tag_cloud', $return, $tags, $args );

    Once you have your function, you must call it somewhere on your theme. Just open the file where you want the list to be displayed (Most of the time it is sidebar.php) and paste the following code:

    <select name="tag-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
    	<option value="#">Liste d'auteurs</option>
    	<?php dropdown_tag_cloud('number=0&order=asc'); ?>

    Now, you have a very cool drop-down list to display you tags. No more unreadables tag clouds!

  • Leave a Comment
  • How To: Displaying Your Most Commented Posts

    Though this isn’t quite the same as displaying your most popular posts in your sidebar, here is some code you can use to display the posts that have received the most comments.  You’ll want to place it in your sidebar where you want the code to be displayed.

    Most Commented Posts Code

    Go into your theme files and go to header.php file.   Somewhere within the </head> you’ll want to place the following code:

    <?php most_popular_posts($no_posts = 5, $before = '<li>', $after = '</li>', $show_pass_post = false, $duration='') {
    global $wpdb;
    $request = "SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS 'comment_count' FROM $wpdb->posts, $wpdb->comments";
    $request .= " WHERE comment_approved = '1' AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status = 'publish'";
    if(!$show_pass_post) $request .= " AND post_password =''";
    if($duration !="") { $request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
    $request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
    $posts = $wpdb->get_results($request);
    $output = '';
    if ($posts) {
    foreach ($posts as $post) {
    $post_title = stripslashes($post->post_title);
    $comment_count = $post->comment_count;
    $permalink = get_permalink($post->ID);
    $output .= $before . '<a href="' . $permalink . '" title="' . $post_title.'">' . $post_title . '</a> (' . $comment_count.')' . $after;
    } else {
    $output .= $before . "None found" . $after;
    echo $output;
    } ?>

    If you’d prefer to display more than 5 posts, you can change the $no_posts = 5 code to whatever number you want to display.

    Okay, now, you need to figure out where you want to display these most commented posts (usually the sidebar) and place the following code:

    <?php most_popular_posts(); ?>

    And as is usually the case, if you want something easier, you can always go with a plugin such as the Popularity Contest plugin.

    To see other code that we’ve featured, check out our WordPress Code page.

  • Leave a Comment
  • How to: Create an Ajax-based Auto-completing Search Field for your WordPress Theme

    Why not helping your visitors to find what they’re looking for on your blog, by using a cool auto-completion on your search field? To do so, we’ll use WordPress tagcloud, php and ajax.

    Please note that even if this code is fully functional, this is an experimentation, and the SQL query isn’t really optimized.

    The idea

    We will use tags as a list of keyword to suggest to the readers.

    When someone will start to type on the search field, we will use Javascript to send a request to a php page which will do the following SQL request SELECT * FROM matable WHERE ‘name’ LIKE ‘$search%’. Via Ajax, we’ll send back the request results to our page, and display it to the visitor.

    First part: PHP

    The first thing to do is to create a php page. This page will send a request to our WP database and display the tags as a html unordered list.
    if (isset($_POST['search'])) {
    $search = htmlentities($_POST['search']);
    } else $search ='';
    $db = mysql_connect('localhost','root',''); //Don't forget to change
    mysql_select_db('wp', $db); //theses parameters
    $sql = "SELECT name from wp_terms WHERE name LIKE '$search%'";
    $req = mysql_query($sql) or die();
    echo '<ul>';
    while ($data = mysql_fetch_array($req))
    echo '<li><a href="#" onclick="selected(this.innerHTML);">'.htmlentities($data['name']).'</a></li>';
    echo '</ul>';

    This code is simple: It receive a POST parameter (The letter(s) typed in the search field by the visitor) and then sends a request to our WP database in order to gets all tags starting with the letter(s) typed in the search box.

    Part two: Ajax

    Now it’s time to start the client-side programming. We need to code 4 Javascript functions in order to make our auto-completion work:

    • Function ajax() will create a XMLHTTPRequest object.
    • Function request() will send an Ajax request to our gettags.php file.
    • Function return() will return gettags.php contents.
    • And the selected() function will update the search field.

    Here’s our gettags.js file and the 4 functions needed:
    var myAjax = ajax();
    function ajax() {
    var ajax = null;
    if (window.XMLHttpRequest) {
    try {
    ajax = new XMLHttpRequest();
    catch(e) {}
    else if (window.ActiveXObject) {
    try {
    ajax = new ActiveXObject("Msxm12.XMLHTTP");
    catch (e){
    ajax = new ActiveXObject("Microsoft.XMLHTTP");
    catch (e) {}
    return ajax;
    function request(str) {
    //Don't forget to modify the path according to your theme"POST", "wp-content/themes/openbook-fr/gettags.php");
    myAjax.onreadystatechange = result;
    myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    function result() {
    if (myAjax.readyState == 4) {
    var liste = myAjax.responseText;
    var cible = document.getElementById('tag_update').innerHTML = liste;
    document.getElementById('tag_update').style.display = "block";
    function selected(choice){
    var cible = document.getElementById('s');
    cible.value = choice;
    document.getElementById('tag_update').style.display = "none";

    Part three: Editing your theme

    Now that we have our php and javascript ready, we can edit the searchform.php file from your WP theme:

    Your searchform.php file should look like this:
    <form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
    <input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
    <input type="submit" id="searchsubmit" value="Search" />

    We have to add a div, which will display the received data from the request, as well as a Javascript event on the search form:
    <form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
    <input type="text" value="<?php the_search_query(); ?>" name="s" id="s" onkeyup="request(this.value);"/>
    <input type="submit" id="searchsubmit" value="Search" class="button" />
    <div id="tag_update"></div>

    Final part: CSS

    Due to the fact that every theme use different color schemes, this is only an example. Anyways, I thought it could be a good start:
    #tag_update {
    display: block;
    border-left: 1px solid #373737;
    border-right: 1px solid #373737;
    border-bottom: 1px solid #373737;
    #tag_update ul {
    margin: 0;
    padding: 0;
    list-style: none;
    #tag_update li{
    #tag_update a {
    display: block;
    padding: .2em .3em;
    text-decoration: none;
    color: #fff;
    background-color: #1B1B1C;
    text-align: left;
    #tag_update a:hover{
    color: #fff;
    background-color: #373737;
    background-image: none;

    That’s all. You now have a very nice auto-completing search form! If you have any questions, feel free to leave a comment below.

  • Leave a Comment
  • How To: Insert Ads Only After the First Post

    Have you ever tried to insert advertisements (or any bit of code really) into the WordPress post loop, then found that it will insert the banner after each post?   It really depends on what you are going for, but this usually will not be an ideal solution to placing advertisements between posts on your homepage.   If you’d like to place something only after the first post in the WordPress post loop, here is a quick hack you can do to tell WordPress to only display it after the first post.

    Simply go to your themes homepage and look for the following code:

    <?php endwhile; ?>

    Immediately before this code, place the following code:

    <?php if(!$show_ads){ ?>
    Insert Code Here
    <?php $show_ads = 1; } ?>

    Obviously you’ll want to replace Insert Code Here with your code.  Told you it was easy!

  • Leave a Comment