Hiding the categories of a post when it is “uncategorized”

If you’ve ever had some posts on your WordPress blog, you will have noticed that the “Uncategorized” category is displayed with a link to an archive of uncategorized posts.

Uncategorized

The easiest way to solve this, of course, is to categorize every blog post. But, if you don’t want to for some reason, you can use some PHP in your theme to hide the category of these posts. The example below is a customization I did for a theme in Bones but it should be easy to follow for other themes as well. The original line for the display of the categories in Bones is:

<?php printf( __( 'filed under', 'bonestheme' ).': %1$s', get_the_category_list(', ') ); ?>

So, it is just using the WordPress function, get_the_category_list, to list a comma-separated list of categories for the post. How do we hide this if the post is uncategorized? Well, one way to do it is to get a list of categories for the post. If the number of categories is one, and that category is “Uncategorized” then we just won’t use the get_the_category_list display. Here is the code:

$show_categories = true;
$categories = wp_get_post_categories( $post->ID );
// We don't want to show the categories if there is a single category and it is "uncategorized"
if ( count( $categories ) == 1 && in_array( 1, $categories ) ) :
 $show_categories = false;
endif;
if ( has_category( null, $post->ID ) && $show_categories ) :
 echo ' <span class="amp">&</span> ' . __('filed under ', 'bonestheme') . get_the_category_list(', ');
endif;

We start off with the assumption that we’ll display the categories so we set a flag as true to begin with. Then, we retrieve the categories for a post. wp_get_post_categories will return the post’s categories as an array. Terms, or categories, for WordPress are stored in the wp_terms database table. And “Uncategorized” is actually a stored term with the term_id of 1:

Uncategorized term in database

With this knowledge, we check the number of categories of our post (retrieved with wp_get_post_categories) with a count call. If the result is one and the category array contains the “Uncategorized” category (term_id of 1) then we know we don’t have any categories we want to display. So, we’ll set our flag to false.

Finally, we make sure that the post does have categories and that our flag to display categories is set to true. WordPress’s has_category function, if given no category to check against, will just tell us if the post has any categories. If the post has categories and the flag is set to true, then we will use the category display line in our theme and display the post’s categories.

Hiding the WordPress admin bar on certain pages

There may be times when you would like to hide the WordPress admin bar on certain pages. Maybe the admin bar interferes with the design, for example. This can be especially true for things like pages opening up in a lightbox. Fortunately, it is not too difficult to hide the admin bar on certain pages with a filter in WordPress.

There is actually a filter in WordPress named, logically enough, show_admin_bar. This filter will show the admin bar if true is returned but not show the admin bar if the returned value is false. You pass the $bool value in which is WordPress’s own determination if the admin bar should be shown or not. So, in your theme’s functions.php file, you can add the following code:

function my_theme_hide_admin_bar($bool) {
if ( is_page_template( 'page-pop-up.php' ) ) :
return false;
else :
return $bool;
endif;
}
add_filter('show_admin_bar', 'my_theme_hide_admin_bar');

In the code above, we are simply checking to see if the page we’re on is using the template file, page-pop-up.php. This is a theme file that I used to display pages opening up in a lightbox. If the page is using that template, we return false to suppress the showing of the admin bar. If not, we return the usual $bool value set in WordPress and it will act as normal. Of course, the template conditional is just one example. You could also use other WordPress conditionals to turn the admin bar off for a myriad of other circumstances.

Conditional Required Contact Form 7 Fields

Sometimes you may want to have a required field in Contact Form 7 only when another form field has a certain value. For example, if someone has an option to choose their preferred method of contact between email and telephone, you’d want to make the email address field or the phone call field required accordingly. This isn’t too difficult to accomplish in Contact Form 7. You can look at how Contact Form 7 validates text and email fields by viewing its code in:

contact-form-7/modules/text.php

Around line 91, you will see the validation filters defined by Contact Form 7:

add_filter( 'wpcf7_validate_text', 'wpcf7_text_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_text*', 'wpcf7_text_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_email', 'wpcf7_text_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_email*', 'wpcf7_text_validation_filter', 10, 2 );

Then, you can look at the function that handles the validation, wpcf7_text_validation_filter. The function accepts two parameters – $result and $tag. The $tag is the field being validated and the $result is, well, the result of the validation. In other words, did something go wrong?

The user-entered text of the field being checked is assigned to $value. Then, the function checks the current tag type. Is it text? Email? And it will process it accordingly. If a value is empty but the field is required, for example, the result will be invalid:

$result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );

In this case the Contact Form 7 error message for required fields is given as an error (wpcf7_get_message( ‘invalid_required’ )). If $result-invalidate() is called, that field will fail validation and you will get a form error.

We’re not, of course, going to modify the plug-in’s files directly. We want to make our plug-in modifications safe from future plug-in updates so we will tie into the same filters that the plug-in uses. I can put this code in my theme’s functions.php file or put it into a my own plug-in. In my example, I am setting two conditional required fields – email and phone number. So, I will need to set my own custom validations for both text and email fields:

add_filter( 'wpcf7_validate_text', 'my_site_conditional_required', 10, 2 );
add_filter( 'wpcf7_validate_text*', 'my_site_conditional_required', 10, 2 );
add_filter( 'wpcf7_validate_email', 'my_site_conditional_required', 10, 2 );
add_filter( 'wpcf7_validate_email*', 'my_site_conditional_required', 10, 2 );

For both the text (phone) and email fields, I am using the function, my_site_conditional_required, for my own custom validations. Here is my complete function:

function my_site_conditional_required($result, $tag) {
    $tag = new WPCF7_Shortcode( $tag );

    $name = $tag->name;

    $value = isset( $_POST[$name] )
        ? trim( wp_unslash( strtr( (string) $_POST[$name], "\n", " " ) ) )
        : '';

    if ( "phone" == $name && 'Phone' == $_POST['contact-method'] ) :
        if ( '' == $value  ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
        endif;
    endif;

    if ( "email" == $name && 'Email' == $_POST['contact-method'] ) :
        if ( '' == $value ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
        elseif ( ! wpcf7_is_email( $value ) ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_email' ) );
        endif;
    endif;

    return $result;
}

Here is how it works. I am doing the same thing that Contact Form 7 does with setting the $value. Then, instead of checking the tag type, I want to check the tag name. I specifically want to look for the fields named “phone” or “email.” I also have a dropdown named “contact-form” so I can check the $_POST value of contact-form and use that to see if the field being checked should be required. If $_POST[‘contact-form’] is equal to “Phone,” I want the phone field to be required:

if ( "phone" == $name && 'Phone' == $_POST['contact-method'] ) :
        if ( '' == $value  ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
        endif;
endif;

I have an extra check for the email. I don’t just want to require the email address, I want to make sure it is a valid email address as well. Contact Form 7 provides a function to check an email, wpcf7_is_email:

elseif ( ! wpcf7_is_email( $value ) ) :

As you can see, my custom function works very similarly to the code in the plug-in. Finally, you probably want to show the user the field that is required based on their downdown selection. I added empty spans after the field labels that I can use to add and remove informational asterisks from:

<label class="email-label">Email<span class="asterisk"></span></label>

Then, I can use jQuery to add and remove the asterisks:

<script type="text/javascript">
 jQuery(function() {
 add_required_asterisks();
 jQuery("select[name='contact-method']").on('change', function() {
 add_required_asterisks();
 });
 });
 function add_required_asterisks() {
 if ( jQuery("select[name='contact-method']").val() == "Phone" ) {
 jQuery(".phone-label .asterisk").html("*");
 jQuery(".email-label .asterisk").html("");
 }
 else {
 jQuery(".phone-label .asterisk").html("");
 jQuery(".email-label .asterisk").html("*");
 }
 }
 </script>

I created a JavaScript function that will see what my dropdown menu (named “contact-method”) is set to and then, based on that, turn the asterisks on or off. Then, I call that function on page load and, whenever the dropdown changes:

jQuery("select[name='contact-method']").on('change', function() {
add_required_asterisks();
});

Quick WordPress Tip – Upload to a Post Without Switching Tabs

Here is a quick tip for WordPress users out there. When you are adding, say, a Featured Image to a post, you are brought to the Media Library window that includes an “Upload Files” tab. This might lead you to believe that you need to switch to that tab in order to upload a new image file. Actually, though, you can save yourself some clicks by simply dragging a photo onto the Media Library. No need to switch tabs.

Drop to Upload

Saving changes made in Chrome’s Web Inspector

It is wonderful to be able to use Chrome’s Web Inspector development tools to tweak the CSS of a web page to get elements just right. However, what is the best way to apply these changes to the actual stylesheet? One could, of course, just move these changes by recreating the tweaks to the CSS document manually. There is a way, though, to actually save out the modified CSS file right from the Web Inspector. To do this, simply click on the CSS link at the right-hand side of the Styles palette:

CSS link

 

Clicking on the link will open up the modified CSS file in the Web Inspector’s Sources tab:

sources

 

Right-clicking on the opened CSS file will allow you to view the changes made to the CSS file via the Elements tool (Local Modifications) as well as save out the changed CSS file which you can use to replace the old CSS.

Right click

Using MailCatcher for local mail testing

When developing web applications on your local machine, you will often want to test e-mails. For the longest time, I would use an environmental switch in PHP depending on the domain (for example, I would set different values if the domain was stirrell.second-cup-of-coffee or www.second-cup-of-coffee.com) and include values for email addresses. I had my local MAMP really sending out emails and this worked fine. Of course, there is always the chance you’re going to miss an email somewhere and inadvertently send out a real email when you just want to test.

A good solution to this problem is to use a “fake” SMTP server – a program that simulates sending an email and allows you to see what would have been sent – but only exists on your local machine. I had been using one on the Macintosh – MockSMTP which is available on the Mac App Store. It had been working fine for me. I set it up according to the instructions here and it all worked swimmingly… until I upgraded to the newest Mac OS X, Mavericks. I did not receive any errors but I also never received any test emails. Bummer. I sent a tweet to the folks who make MockSMTP but never got a response – the app itself has not been updated since 2011 so I fear that an update might not be coming.

I searched around for an alternative to MockSMTP. Many of the ones I saw were Java-based multi-platform solutions which did not appeal to me. I finally decided to give the free MailCatcher a try. MailCatcher is a Ruby Gem so is installed via the command line and called through the command line. I followed the instructions at their site and it worked straight away.

To get MailCatcher working with PHP, I edited the php.ini configuration files to use catchmail for the sendmail path. In MAMP, you simply go to File > Edit Template > PHP and then choose the version of PHP you are using. You can tell what version of PHP you are using with MAMP by going to the “Server” tab:

PHP version

I added the following line to my configuration file:

sendmail_path = /usr/bin/env catchmail

Once that is set, all email sent by PHP will go to MailCatcher. You can view mail sent to MailCatcher using a browser to connect to your local machine on port 1080 (http://127.0.0.1:1080/). You will get a simple web interface for viewing the mails that have come in. From then on, simply type “mailcatcher” in the Terminal to start up MailCatcher. This will give you a simple way of testing emails on your local machine without worry of emails getting sent to the client.

Passing PHP variables to JavaScript

I was recently working on a project in CodeIgniter and I was setting numeric variables with constants for things like locations (1 = Maine, 2 = New Hampshire, etc.). This all worked fine but when it came to doing some JavaScript AJAX work I didn’t have access to these constants. One of the advantages to using these constants is that I did not want to have to change the value in more than one place if a value changed or I wanted to add a new location, for example. My way to solve this was to pass my PHP variables through to JavaScript using json_encode.

In my CodeIgniter controller, I set the variables I wanted to use in JavaScript:

$footerData['javascriptVariables'] = array(
'sheetID' => $sheetID
);

Then, in the footer, I checked for the existence of $javascriptVariables and, if it is not empty, I echoed out the json_encoded value:

// Were there any variables set via PHP for use in the JavaScript?
if (!empty($javascriptVariables)) {
echo "<script type='text/javascript'>\n";
echo "var php_variables = " . json_encode($javascriptVariables) . "\n";
echo "</script>\n";
}

This results in something like:

<script type='text/javascript'>
var php_variables = {"sheetID":"8"}
</script>

Then, in my JavaScript, I can easily get access to the sheetID set in PHP:

php_variables.sheetID

I suspect that I could also automate the process of making all my PHP constants available in JavaScript by using get_defined_constants.

Sublime Text’s Extend Selection to Word in TextMate 2

One of the coolest features of Sublime Text 2, in my opinion, is the ability to use the command, “Extend Selection to Word” with Sublime Text’s multiple cursors. Using this command, one can highlight a word they want to change, select the command (or the key command equivalent) which selects the next instance of the word with multiple cursors and then you can replace both words (or as many words as you select) by typing once. I thought that TextMate 2 was missing this feature and that I would have to replace words one at a time or rely on replacing all within a selection. It turns out, though, that TextMate has this feature as part of the Text Bundle.

By default, the “Extend Selection to Include Next” command is bound to the Control-w keys and is available in the Text bundle under Menu Actions > Selecting.

Extend Selection to Include Next

You can, of course, change the key binding (I made it the same as I have it in Sublime Text 2 – Command-D). I absolutely love this feature and am glad to see that it is available in TextMate 2.

Changing Posts per Page in WordPress admin

Here’s a quick WordPress tip. One thing that always bugged me about the admin interface is that WordPress shows just 20 posts per page in the admin list leading to a lot of clicking the paging navigation. Well, WordPress allows you to change the number of posts shown per page. Go to the Screen Options dropdown at the top of the page. One of the options is the number of posts. Change it to a larger number and deal less with clicking through pages. I never knew about this handy feature until a coworker of mine pointed it out.

Post per post WordPress