Useful WordPress Snippets

Through my experience as a WordPress theme developer I have gathered (and keep finding more) useful pieces of code for my projects. Below is my list of handy snippets that you’re welcome to use in your own development. Enjoy!

I haven’t had time to revise these yet, so some might be a bit outdated.

Removing Extra P Tags & Br | Clean Up WordPress Shortcodes

One of the most annoying issues when dealing with shortcodes in WordPress is that if the content inside the shortcodes has any spacing at the top or bottom the post editor will adding some blank p and/or br tags into the code. This can have a negative affect on the rending of the shortcode, specifically when your theme is applying any sort of styling to the p tags, such as margins. To prevent this you can go in HTML mode and make sure there isn’t any spacing and so forth, however, this can be a real hassle. Below is a small function which will strip away any open p tags before a bracket and closing tags after the bracket as well as any break tags after a closing bracket in the post editor (the brackets are most commonly used for shortcodes – that’s why we target them specifically).

/*--------------------------------------*/
/*    Clean up Shortcodes
/*--------------------------------------*/
function wpex_clean_shortcodes($content){   
    $array = array (
        '<p>[' => '[', 
        ']</p>' => ']', 
        ']<br />' => ']'
    );
    $content = strtr($content, $array);
    return $content;
}
add_filter('the_content', 'wpex_clean_shortcodes');

Adding Taxonomy Name To WordPress Body_Class

Recently a customer of my Office WordPress Theme had their portfolio categories in their main navigation and they wanted to style then based on if the current single portfolio post belonged to that category. So for example if you were on a post that belonged to the category “community” they wanted that “community” link in the navigation to be highlighted.

As you know WordPress automatically adds classes to both the body tag (when the body_class() function is being used) and to the navigation links. The issue is that the WordPress body class doesn’t automatically add taxonomy terms to the body tag so there really wasn’t any way to accomplish what they wanted.

Solution? Use a filter!

I came up with a very simple function that would add any terms from the portfolio_cats taxonomy in the current post to the body class in the format of portfolio-{term}.  This way they could use the body class to properly style the navigation elements.

Hopefully this function proves to be useful to you!

// add classes to body based on custom taxonomy portfolio_cats
function wpex_port_tax_body_class( $classes ) {
    if('portfolio' == get_post_type() ) {
        global $post;
        $terms = get_the_terms( $post->ID, 'portfolio_cats' );
        if($terms) {
            foreach ($terms as $term) {
                $term_classes[] = 'portfolio-' . $term->slug;
            }
            $classes = array_merge( $classes, $term_classes );
        }
    }
   return $classes;
}
add_filter( 'body_class', 'wpex_port_tax_body_class' );

Trim/Limit WordPress Content

WordPress has a cool function called wp_trim_content which will allow you to easily cut off or trim the content in a loop, which is perfect for showing excerpts as an alternative to the_excerpt(). Below is an example of how to use the function to trim your content to 100 words. Of course the function can be used to trim anything! So you can change get_the_content() to any variable or string of text!

<?php echo wp_trim_words( get_the_content(), 100 ); ?>

Redirect All 404 Pages

A quick snippet that will allow you to redirect all of your 404 error pages to the page of your choice so you don’t lose valuable traffic and link juice.

Paste in 404.php

Simply paste the following at the top of your 404.php theme template. It will redirect all 404 pages to your homepage if you want to direct traffic to a URL of your choice then change home_url() to the URL of your choice inside quotes. For more on wp_redirect check out the codex.

<?php
// redirect 404 to homepage
wp_redirect(home_url(), 301); exit; ?>

Check Current WordPress Post Type

I love working with custom post types. I use them here on WPExplorer for videos, coupons, snippets, slides, themes…etc, and of course also use them in my premium themes. Custom post types are only great for organization but also from a design perspective it makes it really easy to give different styles to different posts. Below I show you how you can get the post type for the current post in a loop. Let the possibilities run wild!

Get Post Type

To get the current post type it’s as easy as using the following function:

get_post_type()

Does Current Post Type Match Yours?

This is great for use in loops if you want a post with a certain post type to behave differently.

if(get_post_type() == 'portfolio') { //do something epic }

Basic Colum Shortcode

While I personally like the idea of shortcodes being controlled via plugins, there are some basic shortcodes which are great to have in any theme. One of these is the column shortcode that will allow you to easily create column layouts in your posts and pages. Below I’ve posted a basic column shortcode function which you can use to create half, third, fourth, fifth and sixth column layouts (based on CSS percents).

Column Shortcode PHP

Paste the following function either in your functions.php file or wherever you store your shortcodes functions.

/*---------------------*/
/*    Columns
/*--------------------*/
add_shortcode('column', 'column_shortcode');
function column_shortcode( $atts, $content = null ) {
  extract( shortcode_atts( array(
   'size' => '',
   'position' =>''
  ), $atts ) );
return '<div class="one-'.$size.' column-'.$position.'">'.do_shortcode($content).'</div>'; }

Column Shortcode CSS

Paste into your style.css file or wherever you keep your shortcodes css.

/*columns*/
.one-half{ width: 48% }
.one-third{ width: 30.66% }
.one-fourth{ width: 22% }
.one-fifth { width: 16.8% }
.one-sixth { width: 13.33% }

.one-half,
.one-third,
.one-fourth,
.one-fifth,
.one-sixth {
    position: relative;
    margin-right: 4%;
    float: left;
}
.column-last { margin-right: 0px }
.column-last:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
    font-size: 0;
}

The Shortcode

Now adding the shortcodes is pretty easy. Below is an example of a 2 column layout using these shortcodes. Notice how the last column requires the “last” position value, this is to remove the right-side margin and also clear the floats.

[column size="half"]My Content[/column]
[column size="half" position="last"]My Content[/column]

Limit Search By Post Type

I’ve been using post types a lot lately in my themes and one of the questions I get very often is how users can add a searchform to their site that allows them to search only through 1 specific post type instead of searching through the entire website. Luckily this is very easy to do and can be accomplished with a simple hidden input field in the search form.

Standard Form

Below is a sample of what a searchform might look like on your site:

<form method="get" id="searchbar" action="<?php echo home_url(); ?>/">
<input type="text" name="s" value="<?php _e('search...', 'boxed' ); ?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value='<?php _e('search...', 'office' ); ?>';" id="search" />
<input type="submit" value="" name="submit" id="searchsubmit" />
</form>

Hidden Field

To limit the search to a specific post type all you need to do is add the following hidden field inside the form

<input type="hidden" name="post_type" value="MY_POST_TYPE" id="search-filter" />

Full Code

Below is the entire sample code of your search form that will only search the posts that are a part of “MY_POST_TYPE”.

note: Don’t forget to change where it says “MY_POST_TYPE” to the post type you want to filter out.

<form method="get" id="searchbar" action="<?php echo home_url(); ?>/">
<input type="text" name="s" value="<?php _e('search...', 'boxed' ); ?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value='<?php _e('search...', 'office' ); ?>';" id="search" />
<input type="submit" value="" name="submit" id="searchsubmit" />
<input type="hidden" name="post_type" value="MY_POST_TYPE" id="search-filter" />
</form>


Remove Old Shortcodes

Recently I switched WPExplorer over to a new design and in the process I removed several shortcodes, specifically hr and br shortcodes which I used in various places in the past. The issue is after removing the shortcodes in my functions.php instead of echoing out code, now I have these shortcodes showing up as strings of text in my posts. The following MySQL query helped me remove my old shortcodes and you can edit it to do the same for you.

note: You should always update your database before running any SQL query.

UPDATE wp_posts SET post_content = replace(post_content, '[hr]', '' ) ;

List Shortcodes For WordPress

I’ve added some list shortcodes to my Office WordPress theme (view here) so users can easily create different types of lists via the post editor. The shortcode is extremely easy to add and use so I figured i would share the code I use on my premium theme here so if you want you can add it to your own themes.

The Shortcode

Below is the shortcode which can be inserted either to your functions.php file or an external file you include from the functions.php, I personally put all my shortcodes in a functions folder inside a shortcodes.php file.

/*-----------------*/
/*    Lists
/*-----------------*/
function list_shortcode( $atts, $content = null ){
    extract(
    shortcode_atts( array(
      'type' => ''
      ),
      $atts ) );
        return '<div class="' . $type . '">' . $content . '</div>';
}
add_shortcode('list', 'list_shortcode');

The CSS

As you can see the way the shortcode is going to be setup is that it adds a div around the content inside the shortcode with a class name based on the “type” value from the shortcode. So to style the actual lists I use the following CSS:

 /*lists*/
.check ul { margin: 25px 0 25px 20px; list-style-image: url('images/shortcodes/check.png'); }
.bullets-gray ul { margin: 25px 0 25px 20px; list-style-image: url('images/shortcodes/bullets-gray.png'); }
.bullets-black ul { margin: 25px 0 25px 20px; list-style-image: url('images/shortcodes/bullets-black.png'); }
.bullets-blue ul { margin: 25px 0 25px 20px; list-style-image: url('images/shortcodes/bullets-blue.png'); }
.bullets-red ul { margin: 25px 0 25px 20px; list-style-image: url('images/shortcodes/bullets-red.png'); }
.bullets-purple ul { margin: 25px 0 25px 20px; list-style-image: url('images/shortcodes/bullets-purple.png'); }

As you can see all I’ve done is set the image style of the lists inside that div container. This means that any list inside the shortcode will have that list format. Also, if you want to add list styles directly to your theme, you can add the class anywhere. Even your body class!

The Images

Below are the images so you can save them and use them with your theme.

         

Usage

Using the shortcode is really simple. This is what it would look like in the HTML mode in your post editor:

[list type="check"]
<ul>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
</ul>
[/list]

And of course you would change where it says “check” to the list style you want based on the classes you created in your css file.

Below is a video showing how to use the shortcode with the Classy WordPress Theme as a sample.

Watch Video

Exclude Images Inserted To A Post/Page From Attachment Loop

One of the things I really enjoy about WordPress is using image attachments to create things like galleries or sliders for pages/posts, without having to go through plugins or custom post types. It’s very simple to create an attachment loop and then echo out your images into a slider or grid.

The Problem

The issue is that an Image attachment loop not only adds any images uploaded to your post, but also any images inserted into your post. What if you want to insert an image to the post and exclude it from the gallery or slider?

The Solution

The best solution I’ve found was over on WPQuestions, an answer by “Kailey Lampert”. So basically any image you insert to a post/page has a wp-image-{n}’ class name, so you can use a regex that looks for images with that class name in the post content and extracts their ID numbers and set’s them in an array, so we can then exclude them from our get_posts loop. See below:

//find images in the content with "wp-image-{n}" in the class name
preg_match_all('/]?class=["|\'][^"]*wp-image-([0-9]*)[^"]*["|\'][^>]*>/i', get_the_content(), $result);

//set exclusion variable
$exclude_imgs = $result[1];

//attachment loop
$args = array(
	'order => 'ASC',
	'post_type => 'attachment',
	'post_parent => $post->ID,
	'exclude => $exclude_imgs, // <--
	'post_mime_type' => 'image',
	'post_status => null,
	'numberposts => -1,
);

Remove All Featured Images In Loop

When updating my WPExplorer design I wanted to change the look of my blog so that posts would have a large full-width featured image, but I didn’t want my old posts to show the old small thumbnail I was using before. So I decided the best solution would be to remove all the old featured images and only have them on the newer ones using the new large image size.

Anyway, removing featured images from your old posts is super easy. All you need to do is use the “update_post_meta” function to set your thumbnail_id for your posts to a null value. Simply paste the code below into your loop to remove the featured images for that loop or create a  function and use get_posts to call the posts you want to remove the images from and then attach to the init hook.

update_post_meta( $post->ID, '_thumbnail_id', '' );

Caution: Backup your database just in case you change your mind. This will remove ALL the featured images from the posts in that loop.

Reminder: Don’t forget to remove the function after it runs once, so you can add new featured images in the future.

Add Item To WordPress Menu Using wp_nav_menu_items

Working on a premium theme I wanted to add a homepage icon at the front of my main menu instead of a standard home text link. However, I didn’t want users to have to add special classes or whatever via the menu dashboard, in stead I wanted it to be added automatically to the first li item of the menu. Luckily there is a very handy “wp_nav_menu_items” hook, that allows you to super easily add items to menu. Anyway, below is the code I used in my project to add a homepage link to the menu with a span as the link value.

//add home icon to menu
 function nav_home_icon($items) {
 $home_icon = '<li><a href="' . home_url( '/' ) . '"><span class="icon-home"></span></a></li>';
 $items = $home_icon . $items;
 return $items;
 }
 add_filter( 'wp_nav_menu_items', 'nav_home_icon' );

Create A Dropdown of Taxonomy Terms In SMOF

A quick snippet showing you how to create an array of terms from your custom taxonomy to use as a dropdown option in the Slightly Modified Options Framework (SMOF). Simply copy the following code, add to your theme-options.php file and replace the word “supersized” and “supersized_cats” to match your taxonomy name.

 //Access Supersized Slides via an Array
$supersized_args = array( 'hide_empty' => '0' );
$supersized_terms = get_terms('supersized_cats', $supersized_args);
$supersized_tax = array();
foreach ( $supersized_terms as $supersized_term) {
    $supersized_tax[$supersized_term->term_id] = $supersized_term->slug;
}
$supersized_tax_tmp = array_unshift($supersized_tax, "Select a category:");

Excerpts By ID

The following function will allow you to pass the ID or object of your post and return the excerpt. The function will also allow you to set the length of the excerpt, the HTML tags that are allowed and any extra content to append at the end of your excerpt.

The Function

/*
* Gets the excerpt of a specific post ID or object
* @param - $post - object/int - the ID or object of the post to get the excerpt of
* @param - $length - int - the length of the excerpt in words
* @param - $tags - string - the allowed HTML tags. These will not be stripped out
* @param - $extra - string - text to append to the end of the excerpt
*/
function pippin_excerpt_by_id($post, $length = 10, $tags = '<a><em><strong>', $extra = ' . . .') {

	if(is_int($post)) {
		// get the post object of the passed ID
		$post = get_post($post);
	} elseif(!is_object($post)) {
		return false;
	}

	if(has_excerpt($post->ID)) {
		$the_excerpt = $post->post_excerpt;
	} else {
		$the_excerpt = $post->post_content;
	}

	$the_excerpt = strip_shortcodes(strip_tags(stripslashes($the_excerpt), $tags));
	$the_excerpt = preg_split('/\b/', $the_excerpt, $length * 2+1);
	$excerpt_waste = array_pop($the_excerpt);
	$the_excerpt = implode($the_excerpt);
	$the_excerpt .= $extra;

	return apply_filters('the_content', $the_excerpt);

Usage

echo pippin_excerpt_by_id($your_post_object);

or

echo pippin_excerpt_by_id($your_post_object, 20, '<a><em>', '');

Hide Post View & Preview Buttons From Custom Post Types

I have always used custom post types for things like image sliders, homepage highlights, testimonials..etc. And sometimes these posts are used for nothing more then the homepage or specific templates, therefore I redirect the single posts for these custom post types to the homepage as they hold no real value (best for SEO and user friendliness).

Anyway, so if you are doing what I’m doing it’s probably best to disable the user from clicking the “Preview” or “View Post” buttons created in the admin panel. To do this I just use a simple css added to the admin on my custom post type pages to hide the buttons. So they are still in the code but not on the front end (a dirty but useful trick). Below is the code I use:

// Admin Custom Post Page Specific CSS
function posttype_admin_css() {
    global $post_type;
    if($post_type == 'postype1' || $post_type == 'postype2' || $post_type == 'postype3') {
    echo '<style type="text/css">#view-post-btn,#post-preview{display: none;}</style>';
    }
}
add_action('admin_head', 'posttype_admin_css');

List Posts By Custom Taxonomy

The code below is a sample of how I display snippets at WPExplorer.com so each snippet is under it’s corresponding category. It’s a loop that will go through your custom taxonomy (such as your custom post type categories) and display all the posts under their corresponding taxonomy.

Simply change your variables at the top and this snippet will display your taxonomies in <h2> tags with the posts from that taxonomy below as a simple list.

<?php
   $tax = 'snippet_categories'; // set this to your taxonomy name
   $posttype = 'snippets'; // set this to your post type name
   $number = '-1'; // the number of posts to show per taxonomy term

   $terms = get_terms($tax,'orderby=custom_sort');
   foreach($terms as $term) {
?>

<h2><a href="<?php echo get_term_link($term->slug, $tax); ?>" title="<?php echo $term->name; ?>"><?php echo $term->name; ?></a></h2>
 <ul>
 <?php
 $tax_query = array(
 array(
 'taxonomy' => $tax,
 'terms' => $term->slug,
 'field' => 'slug'
 )
 );
 $term_post_args = array(
 'post_type' => $posttype,
 'numberposts' => $number,
 'tax_query' => $tax_query
 );
$term_posts = get_posts($term_post_args);
 foreach ($term_posts as $term_post) {
 ?>
 <li><a href="<?php echo get_permalink($term_post->ID); ?>" title="<?php echo get_the_title($term_post->ID) ?>"><?php echo get_the_title($term_post->ID) ?></a></li>
 <?php } ?>
 </ul>
 <?php } ?>

Display Posts By Category

If you are looking to create a cool layout where you display a list of categories with their corresponding posts below, the following snippet is great. You can use it in category.php and it will show the current category title and below a list of the posts included dynamically.Perfect for sites where you use multiple child categories so you can have lets say “Movies” and then under it the child categories “action, adventure, drama” listed with their corresponding posts below each.

<?php
//Identify current Post-Category-ID ermitteln
foreach((get_the_category()) as $category)
    {
    $postcat= $category->cat_ID;
    $catname =$category->cat_name;
    }
?>
<h2><?php echo $catname; ?></h2>
<?php $categories = get_categories("child_of=$postcat");
    foreach ($categories as $cat)
    { ?>
    <?php query_posts("cat=$cat->cat_ID&posts_per_page=-1"); ?>
    <h3><?php single_cat_title(); ?></h3>
    <?php while (have_posts()) : the_post(); ?>
    <ul>
        <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
            <?php the_title(); ?></a>
        </li>
    </ul>
    <?php endwhile; ?>
    <?php } ?>
<?php } ?>

 

Enable Maintenance Mode

A quick and dirty code snippet to set your site in maintenance mode so only the administrators can have access to your site as it will be disabled for regular visitors.

function wpexplorer_maintenance_mode() {
    if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) {
        wp_die('Maintenance, please come back soon.');
    }
}
add_action('get_header', 'wpexplorer_maintenance_mode');

You might also be interested in the awesome “Coming Soon & Maintenance WordPress Theme

Restrict Access To Menu Items On A Per-User Basis

A snippet that will allow you to easily restrict admin menu pages from a specific user. Great for restricting client access on a site.

Replace “restricted-user” with the name of the username you want to restrict and then edit the array accordingly for the pages you want to restrict.

function remove_menus()
{
    global $menu;
    global $current_user;
    get_currentuserinfo();

    if($current_user->user_login == 'restricted-user')
    {
        $restricted = array(__('Posts'),
                            __('Media'),
                            __('Links'),
                            __('Pages'),
                            __('Comments'),
                            __('Appearance'),
                            __('Plugins'),
                            __('Users'),
                            __('Tools'),
                            __('Settings')
        );
        end ($menu);
        while (prev($menu)){
            $value = explode(' ',$menu[key($menu)][0]);
            if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
        }// end while

    }// end if
}
add_action('admin_menu', 'remove_menus');

Get Parent Page Title

A WordPress snippet showing you how to get the title of the current page’s parent. Good for use in conditional statements.

Get & Echo Parent Page Title

//get parent page title
$parent_page_title = get_the_title($post->post_parent);

//display parent page title
echo $parent_page_title;

Use As A Conditional

 //If pagent page is Portfolio
 if($parent_page_title == "Portfolio") {
 //do something
 } else {
 //do something else
}

Check if Visitor Is Using IE

A snippet that will allow you to test if a visitor is using Internet Explorer on a WordPress site. Great for telling people their browser sucks.

global $is_IE
if($is_IE) { echo 'Your Browser Sucks'; }

Featured Image URL

The following WordPress snippet will allow you to get the URl (src value) of the current post’s featured image. This is especially useful when you want to open the original image using a lightbox script.

<?php
 $img_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "Full");
 echo $img_url[0];
 ?>

The default image sizes in WordPress are “thumbnail”, “medium”, “large” and “full”. So you can exchange the text that says “full” to get the URL to any of these image sizes or of an image size you’ve defined yourself.

Allow Shortcodes In Widgets

Shortcodes are awesome for expanding the functionality of your WordPress themes, however, by default they only work in the post editor. The following filter will allow you to easily add shortcodes to your widgets. Ideal for use on the default text-widget for buttons, contact forms, videos…etc.

<?php add_filter('widget_text', 'do_shortcode') ?>

Allow HTML In Category Descriptions

On a site I worked on a while back I needed to have text and HTML on my category pages. After some research I found a really great solution by Appthemes which allows you to remove the HTML filters placed on the Category field thus rendering any HTML added to this field. This way I could keep everything neatly in the dashboard.

Code To Remove Filters

Insert into your functions.php file or wherever you keep your main functions.

$filters = array( 'pre_term_description' );
foreach ( $filters as $filter ) {
    remove_filter( $filter, 'wp_filter_kses' );
}
foreach ( array( 'term_description' ) as $filter ) {
    remove_filter( $filter, 'wp_kses_data' );
}

Code to Display Category Description

Below is the code you want to insert either into your category.php or archive.php file to show your descriptions with HTML

$category_description = category_description();

if ( ! empty( $category_description ) )
    echo apply_filters( 'category_archive_meta', '<div>' . $category_description . '</div>' );

Apply Custom CSS To WordPress Admin Area

Who knows why you would ever need to do this, but this is a fun little snippet to add custom css to your WordPress admin area. In the example below I’ve edited the admin area to use “Helvetica Neue” as the default body font by applying the custom_admin_css function which contains my in-line css to the admin_head hook.

function custom_admin_css() {
   echo '<style>
     body{
       font-family: "Helvetica Neue";
     }
   </style>';
 }
add_action('admin_head', 'custom_admin_css');

Check If Post Content Is Empty

A simple code snippet to test if the content of your current post is blank or not. I’ve used it in loops (such as a search page) to exclude posts that don’t have content. Another reason to use this is in custom post types where you are using the main content as a description of sort together with meta options and you want to show an alternative string or value if the post content is empty.

Test If The Post Content Is Empty

Use the following code to test if the current post’s content is empty/blank.

if(empty($post->post_content)) { do something }

Check If Post Content Isn’t Empty

Use the following code to test if the current post’s content is NOT empty/blank.

if(!empty($post->post_content)) { do something }

Get The Slug Of Current Post

Small WordPress code snippet showing you how to get the slug of the current post.

$slug = basename(get_permalink());

WordPress Featured Image JPEG Quality Adjustment

WordPress by default crops featured images with JPEG format to 90% of their default quality to ensure speedy response time for your site. If you wish to adjust the quality of these images you can use the following filter:

add_filter( 'jpeg_quality', 'my_jpeg_quality' );
function my_jpeg_quality( $quality ) { return 100; }

Simply change the return value to the quality you wish and paste into your functions.php or wherever else you see fit. I have set it to 100 in the example which means the image will retain 100% of it’s original display quality.