How to fix UTF-8 filename issues when using wp_handle_upload()

PHP said the file didn’t exist. Except it did.

file_exists() wasn’t working for a file uploaded using wp_handle_upload(). It worked for every other file, except for one provided by a German customer.

I confirmed the following:

  • The file did exist in the correct wp-uploads sub-directory
  • The file had correct permissions
  • The directory and its parents had correct permissions

I was stumped.

Then I renamed the file

I converted indlæsning to indlaesning and it worked. The problem was with UTF-8 characters in the filename.

But how can this be? Let’s see where the file name comes from:

  • _wp_handle_upload() calls
  • wp_unique_filename() to generate a unique file name, which calls
  • sanitize_file_name() to prepare the file name
  • sanitize_file_name() then checks against a list of special characters that are not allowed in file names:
$special_chars = array("?", "[", "]", "/", "\\", "=", "", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+", chr(0));

This list of characters can be modified using the sanitize_file_name_chars filter, but that seemed more complicated than I wanted.

The sanitize_file_name() function also includes a sanitize_file_name filter, which allows you to modify the name of the file after it’s already been sanitized.

Luckily, WordPress already has a function to convert other UTF-8 characters into Latin equivalents: remove_accents(). I used that to convert the filename into something file_exists() could handle.

Here’s how to fix UTF-8 issues with wp_handle_upload()

That converted the filename from: indlæsning.csv to indlaesning.csv. Note that the æ character got converted to ae.

The result? Finally, file_exists().

Fixing JSON Parse Error in WordPress Plugins

If you write WordPress plugins and make AJAX requests, you may be familiar the dreaded Javascript error: SyntaxError: JSON Parse Error: Unrecognized token '>'

SyntaxError: JSON Parse Error: Unrecognized token '<'

Why? Why!?!

What it means is that the response your code expected is screwed up because a plugin barfed PHP warnings into the admin-ajax.php ventilation system.

When WP_DEBUG is on, admin-ajax.php responses can include junk HTML output from PHP warnings, like:

<br />
<b>Notice</b>:  Undefined offset: 0 in
<b>/wp-content/plugins/im-gonna-break-ur-ajax.php</b> on line
<b>666</b><br />

The fix? Catch exceptions, then exceed expectations

The way to fix this is to wrap the jQuery.parseJSON() function in try/catch. That will make sure that the code doesn’t fully blow up.

try {
  jQuery.parseJSON( response );
} catch( exception ) {
  console.log( exception );
}

That will prevent your code from breaking, but it won’t make your code work.

The cause of the code breaking is the junk HTML at the beginning on the AJAX response. So, what we want to do is:

  1. Check for a valid JSON response
  2. If the JSON is invalid, strips all characters until finding a JSON-style opening of {".
  3. Check the newly stripped string to see if that is valid JSON
  4. If valid, return the JSON. If not, return an error message.

Here’s the code to achieve that:

Let me know what you think, and please fork the Gist if you have any improvements!

How to use your own widget icon in the WordPress Widget customizer

Customize WordPress Widget IconIn developing deeper integration with the Customizer functionality of WordPress, I wanted to use a custom icon for my IDX+ plugin’s widgets.

By default, WordPress defines a list of icons using their dashicons icon set and tries to guess the best icon for your widget based on the CSS class of your widget.

Check out the CSS in customize-widgets.css starting on line 415.

For instance, if your widget’s CSS class contains “music”, “radio”, or “audio”, you will have the format-audio dashicon applied to your widget.

How to change the widget icon

Using Dashicons

Note: In order to choose a new icon, go to the Dashicons website and click on the icon you want to use, then click on the “Copy CSS” link to get the correct CSS content value.

#available-widgets [class*=YOUR_CSS_BASE] .widget-title:before{
    content: "\f217"; /* <-- replace this value */
}

Using your own icon font

#available-widgets [class*=YOUR_CSS_BASE] .widget-title:before{
    font-family: idx-plus!important; /* <-- replace this value */
    content: 'd'; /* <-- replace this value */
}

If you want the icon to change color when it’s hovered over, use the following code:

#available-widgets [class*=YOUR_CSS_BASE]:hover .widget-title:before{
    color: #7da838!important; /* <-- replace this value */
}

I hope this helps!

How to remove WangGuard honeypot fields

WangGuard is a great plugin for blocking spam registrations. Without it, this site gets about 50 per day. No good!

I did encounter an issue, however: The <![if !IE]> tag was showing on my registration form for some reason. The code WangGuard adds inside the tag is used to generate a “honeypot” section: spam bots see the fake form fields but users don’t. Spam bots fill out the fields and when the form is submitted, WangGuard sees that the fake fields are filled in and knows the user is spam. The good news is that WangGuard still works without the honeypot fields.

Add the code below to your functions.php file to remove the honeypot fields:

/**
 * Get rid of WangGuard's honeypot fields on the registration form
 */
function kws_remove_wangguard_honeypots() {
    $i = 1;
 
    // WangGuard generates actions in a random position between 1 and 10, 
    // so we remove all actions that may exist.
    while($i < 11) {
        remove_action('register_form','wangguard_add_hfield_1' , $i);
        remove_action('register_form','wangguard_add_hfield_2' , $i);
        remove_action('register_form','wangguard_add_hfield_3' , $i);
        remove_action('register_form','wangguard_add_hfield_4' , $i);
        $i++;
    }
}
 
add_action('plugins_loaded', 'kws_remove_wangguard_honeypots');

Prevent Refresh from Adding Another Product in WooCommerce

Update: this issue has been resolved. WooCommerce now replaces the `add-to-cart` query arg with `added-to-cart` on success.

Prevent items from being mistakenly added to the cart multiple times.

Mountain America Jerky uses the WooCommerce eCommerce plugin for WordPress, and they were having an issue: when users added a product to their cart then refreshed, the item was being added again. Also, when customers added items to their cart, then hit back, they got the dreaded “Confirm Form Resubmission” notice.

To solve this issue, I added a redirection when users added products to their cart. The code hooks into WooCommerce’s `woocommerce_add_to_cart_action` function, located in `/woocommerce/woocommerce-functions.php`.

Here’s the code that you should add to your theme’s `functions.php` file, or to your own custom plugin:

add_action('add_to_cart_redirect', 'resolve_dupes_add_to_cart_redirect');
 
function resolve_dupes_add_to_cart_redirect($url = false) {
 
     // If another plugin beats us to the punch, let them have their way with the URL
     if(!empty($url)) { return $url; }
 
     // Redirect back to the original page, without the 'add-to-cart' parameter.
     // We add the `get_bloginfo` part so it saves a redirect on https:// sites.
     return get_bloginfo('wpurl').add_query_arg(array(), remove_query_arg('add-to-cart'));
 
}

I hope this helps someone else with the same issue!

Paginate Links in WordPress Link Manager

Links are not first-class citizens in WordPress

In developing the a website for professional genealogists, I was tasked with creating link directory functionality in WordPress. I didn’t want to install some big plugins; I wanted to use the Links Manager that’s built in to every WP install out of the box. There were two problems, however:

  1. Link categories are not hierarchical, and;
  2. There is no pagination in the Links Manager: all links are displayed on one page by default.

My client’s website will have over 20,000 links; having them all on one page was simply not an option.

I didn’t want to create a new Post Type or Taxonomy; Links are already the right tool for the job. I moved forward creating the custom solution, and am sharing the results of that development here. The result of the project was a successful deployment of a crazy amount of links (see an example on their Iowa genealogy resources page). Continue reading “Paginate Links in WordPress Link Manager”

Storing Data in WordPress Plugins – A Quick Rundown

Coding better WordPress plugins

As I’ve worked with WordPress plugins, I’ve learned new ways of working with WordPress. WordPress has tons of built-in functionality that is very useful and easy to use once discovered.

I am by no means a great PHP coder. I am still learning OOP principles and how to write code better. In creating new WordPress plugins (see a list of my plugins), I have improved how I code: writing more efficient code using WordPress functionality rather than hacks.

One of the methods of coding that I have discovered (thanks to Jeremy Clarke) is using the WP Cache and Transient APIs to store plugin data. It’s made a big difference in the speed of all my plugins.

The following is a quick review of three different ways of storing data when you code plugins or work with WordPress. This is to the best of my knowledge, and I welcome feedback/improvements in the comments. Continue reading “Storing Data in WordPress Plugins – A Quick Rundown”

Auto-Optimize WordPress Database without a Plugin

These horses are somehow not cool. Speeding up your blog is.

I am working on a WordPress project that has a pretty heavy database, and I want to be able to auto-optimize the WordPress database. Even though they are integrating this functionality into WordPress 3.0, I want it now, and without having to use a plugin (I have had some issues with WP-DBManager configuring properly on a few sites).

If you add the following code to your functions.php file, it will automatically optimize your WordPress database every 6 hours, keeping it squeaky clean. Continue reading “Auto-Optimize WordPress Database without a Plugin”

How to Prevent Loading WP-DownloadManager's CSS File

Stop loading WP-Downloads CSS File

If you want to disable the WordPress plugin WP-DownloadManager‘s download-css.css file from being loaded, add the following code to your functions.php file:

remove_action('wp_print_styles', 'downloads_stylesheets');

Alternatively, if you would just like to use your own stylesheet, you can add a file named download-css.css to your theme’s directory, and the plugin will automatically load your stylesheet instead.

Add a Store Catalog XML Sitemap to the Shopp Plugin

The Shopp default RSS/XML/Google Base solution was not enough.

RSS Feed, BABY!

I needed to have a Google Base feed that featured all the store products. For some reason, the recommended process wasn’t working for me. It was either showing only recent products, or it wasn’t working at all.  Here’s how I fixed it: Continue reading “Add a Store Catalog XML Sitemap to the Shopp Plugin”

Simple Taxonomies Formatting — Improve the Plugin's Code Output

Making the Simple Taxonomies WordPress Plugin Semantic

I’ve been using Joost de Valk’s Simple Taxonomies plugin for a couple of projects, and I’ve been very disappointed by the formatting of the terms output code.

When configuring the plugin, you have the option of choosing “Add terms to the end of posts” or “Add terms to the end of excerpts.” If you do, you get a <div> and a couple of spans. Not very semantic. Also, the code uses an #id, instead of a .class, meaning that if you have more than one post on a page with taxonomies, it no longer validates.

Simple Taxonomies uses terms, so let’s make a list of them!

Here’s a way to reformat the code and prevent overwriting in future plugin updates. We’re going to strip the code and use a definition list instead (<dl>). Definition lists in HTML have a term and description; just as a custom taxonomies creates a taxonomy and its terms. Continue reading “Simple Taxonomies Formatting — Improve the Plugin's Code Output”

How to Display a Random Testimonial or Post in WordPress

Set up a testimonials category — no need for a plugin.

There are a couple of plugins designed specifically for testimonials, but I didn’t want to use them; they use their own databases, and don’t keep with WordPress’ simplicity. If possible, the best way to work with WordPress is to use it’s built-in functionality.

I also wanted to have the testimonials as a category in WP, rather than as a separate plugin. This code will work for any type of category, not just a testimonial.

Here’s how to create a random post item in your sidebar: Continue reading “How to Display a Random Testimonial or Post in WordPress”

Get Adjacent Images – More WordPress Functions

Get the adjacent photo, man.

WordPress, just get the adjacent image links. I’ll tell you what to do with them!

WordPress is normally great about providing functions that have a return and an echo version.  In WordPress, if a function has the prefix get_, then it does not echo (print it into the content), but rather returns the result so that it can be saved as a variable, like so:  $example = get_example();

There are some functions that only have echo capability, so I wanted to share my work-around with you all.

Updated image_link functions

  • adjacent_image_link() » get_adjacent_image_link()
  • previous_image_link() » get_previous_image_link()
  • next_image_link() » get_next_image_link()

Continue reading “Get Adjacent Images – More WordPress Functions”

WordPress Digg Shortcode Function – As Seen on WordPress.com

When moving from WordPress.com, my Digg shortcodes broke.

I wanted a simple way to transition my Digg chicklets to a WordPress.org installation.

I created a function that does nothing special, except for reproducing the Digg shortcode functionality on WordPress.com. All you need to do is enter [digg=http://digg.com/path_to_story_on_digg], and it will create a Digg This chicklet for you. Here’s the code in action →

Continue reading “WordPress Digg Shortcode Function – As Seen on WordPress.com”

Mountain America Jerky Redesign Launched

Mountain America Jerky Redesign

Mountain America Jerky Before Redesign Mountain America Jerky - After Redesign
Mountain America Jerky - Before and After Redesign

I’m happy to announce that today the new Mountain America Jerky website launched. Check out the site and try some of their crazy-good Garlic Black Pepper Beef Jerky. One perk of working with a nice client who sells beef jerky is getting samples of the product! Seriously, though, it’s the best jerky I’ve ever had.

I started working with Mountain America Jerky as a SEO. Jerky is a competitive field, and they wanted to improve their ranking. After working with Chuck on the website’s optimization, he told me he wanted to go big and rebrand the site. The result is a rustic, functional, beautiful website. Continue reading “Mountain America Jerky Redesign Launched”

SEO Randomizer: Save the Value of Your SEO'd Links

Search engines attribution link value is falling for SEOs and web designers.

Update: Now use the SEO WordSpinner plugin to implement this concept.
Use the get_seo_spin() PHP function in your theme’s footer.php file.

Footer links are dropping in SEO value

How to stay relevant while getting great links

As a web designer and SEO, I place links in the footers of most of my designs. Clients don’t mind (I always request the link), and it’s a high-quality link. Most small web design and SEO companies do.  Footer links have become very spammy, however, and sites try to stuff as many links there as possible.

SEOmoz has an article about footer link optimization and claims that

Footer links may be devalued by search engines automatically
Check out the evidence – Yahoo! says they may devalue footer links, Bill Slawski uncovers patents suggesting the same and anecdotal evidence suggests Google might do this (or go further) as well. Needless to say, if you want to make sure your links are passing maximum value, it’s wise to avoid the footer (particularly the footer class itself).

The era of the PageRank-passing footer links are coming to an end. The search engines have a good reason for devaluing the links — but how can we get the juice back?

Let’s consider the following issues:

Nofollow SEO for your WordPress Functions

Link Condom
Pretty crude idea of nofollow, isn't it?

While working on a recent website, I became frustrated by the lack of nofollow support in many WordPress functions.  Make that, most WordPress functions.

There are a few WP functions that I wanted to add nofollow to, so here’s a list and a download link: Continue reading “Nofollow SEO for your WordPress Functions”

Simple Vertical Align Plugin for jQuery

Everything in it's right place.
Sometimes you may want to vertically align a block item, but the CSS-only vertical aligning methods don’t make you feel clean.  Personally, I hate having to style items as a table/table cell to get them to vertically align in Internet Explorer.

jQuery to the rescue.  Using a jQuery vertical align snippet as my base code, I modified it to be a jQuery plugin that will allow you to use the function in the jQuery chain. Continue reading “Simple Vertical Align Plugin for jQuery”

How to View All (or more) Posts at once in WordPress Administration

Here’s the deal: I wanted to be able to temporarily see all the posts at once in the WordPress Administration, so I went into the wp-admin folder, and poked around, and became frustrated: it wasn’t that simple!

Go to /wp-admin/includes/post.php and scroll to line 517. You will see
wp("post_type=post&what_to_show=posts$post_status_q&posts_per_page=15&order=$order&orderby=$orderby");

Change the posts_per_page value to whatever you want it to be. Note: deleting the code will not let you view all posts.

WARNING: I don’t ever like to modify the default WordPress files, because when they get updated, you’ll be screwed. This is a only a temporary fix. It will not last if you update WordPress.