Navigation

Code Snippets
sublime_text
My Top WordPress Code Snippets

I have been developing WordPress themes for about 3 years now and there are a few snippets I use in every theme I build and some that I have used only a handful of times. They have come in handy and have saved my rear end countless times when a client wants something completely custom and the normal WordPress functionality can’t give that to me.  My first snippet I use on every portfolio site or gallery website that I build.

1. Get Attached Post Images In A List

This snippet allows the developer to pull the post images like they were a gallery but manipulate them more then the gallery short code allows you to. You can create an image slider, or a custom gallery. First post this snippet into your functions.php file.

// Get attached images & spits out a list of them.
function project_images($size = 'slider-thumb', $limit = '0', $offset = '0') {
    global $post;
    $images = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
    if ($images) {
        $num_of_images = count($images);
        if ($offset > 0) : $start = $offset--; else : $start = 0; endif;
        if ($limit > 0) : $stop = $limit+$start; else : $stop = $num_of_images; endif;
        $i = 0;
        foreach ($images as $image) {
            if ($start <= $i and $i < $stop) {             $img_title = $image->post_title;   // title.
            $img_description = $image->post_content; // description.
            $img_caption = $image->post_excerpt; // caption.
            $img_url = wp_get_attachment_url($image->ID); // url of the full size image.
            $preview_array = image_downsize( $image->ID, $size );
            $img_preview = $preview_array[0]; // thumbnail or medium image to use for preview.
            ?></pre>
<ul>
	<li>
                <img title="<?php echo $img_title; ?>" alt="<?php echo $img_caption; ?>" src="<?php echo $img_preview; ?>" /></li>
</ul>
<pre>

           }
        }
    }
};

After you have added that to your function.php file you will add the next code snippet to your single.php or which ever file is pulling the post you are editing.  This snippet will output the list on to your page.

<!--?php project_images('full','0','0'); ?-->

you can place the above snippet inside a image slider or just float the images left to create a gallery.

2. Add Support for Thumbnails

Add this snippet into your functions.php file to add different thumbnail sizes to use in your theme files.

// Thumbnail Support

if ( function_exists( 'add_theme_support' ) ) {
	add_theme_support( 'post-thumbnails' );
        set_post_thumbnail_size( 150, 150 ); // default Post Thumbnail dimensions
}

if ( function_exists( 'add_image_size' ) ) {
	add_image_size( 'small-thumb', 183, 141, true ); //Small Thumbnail
	add_image_size( 'header-image', 1000, 550, true ); //Header Image
}

3. Related Posts By Category

Use this code snippet to show related posts by category at the bottom of your posts page. Great for blogs, stores, or portfolio sites. Add this to the bottom of your single.php file.

<!--?php $related = get_posts(  array( 'post_type' =--> 'project', 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 10, 'orderby' => 'post_date', 'order' => 'ASC' ) );
if( $related ) foreach( $related as $post ) {
setup_postdata($post); ?>

<li<!--?php if ( $post--->ID == $wp_query->post->ID ) { echo ' class="current"'; }
else {} ?>>

<!--?php } wp_reset_postdata(); ?-->
Genesis Design Palette Pro

4. Related Posts By Tag

Use this snippet if you you are using tags to relate your posts. Add this snippet to the bottom of your single.php file.

<ul class="related">
<?php
//for use in the loop, list 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
  $first_tag = $tags[0]->term_id;
  $args=array(
    'tag__in' => array($first_tag),
    'post__not_in' => array($post->ID),
    'showposts'=>5,
    'caller_get_posts'=>1
   );
  $my_query = new WP_Query($args);
  if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>

      <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_post_thumbnail( 'more-thumb' ); ?></a></li>

      <?php
    endwhile;
  }
}
?>
</ul>

5. Pull The Featured Post

You can use this code snippet any where just change the cat=4 to whatever the ID of your featured category is. This is great if you just want to display 1 post and you want to choose what post that is!

     <!--?php      global $cat;      $recentPosts = new WP_Query(); 	 $recentPosts--->query('showposts=1&cat=4');
	 ?>
     <!--?php while ($recentPosts--->have_posts()) : $recentPosts->the_post(); ?>
     <!--?php if (has_post_thumbnail()) { ?-->

     <!--?php } ?--></pre>
<div class="content">
<h6></h6>
 <!--?php the_excerpt() ?--></div>
<pre>
<!--/content-->
     <!--?php endwhile; ?-->

6. Get The Featured Image Of The Next Post

I don't use this code snippet in every theme I build but i use it in most portfolio websites. I like to make the portfolio themes function so that when you are on a project at the end of the slider you have the chance to go to the next post. This code snippet allows you to do that but instead of just saying next post you see the

<?php
$next_post = get_adjacent_post( true,'',true );
if( isset($next_post->ID) ):
    $next_id = $next_post->ID;
else:
    $next_post = new WP_Query( 'posts_per_page=1&post_type=project&order=ASC' );
    $next_id = $next_post->post->ID;
endif;
?>

<a href="<?php echo get_permalink( $next_id ); ?>">
    <?php echo get_the_post_thumbnail( $next_id, 'next- thumbnail' ); ?>
</a>

7. Get Featured Image and Use as Background

This is another plugin i don't use all of the time but has come in handy more then once. It takes your post's featured image and makes it the background image of the site for that page. Add this code snippet to your header.php file.

<?php global $post; ?>
<?php
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 56000,50000), false, '' );
?>

<div class="bg-image">
<div class="wrapper" style="background: url(<?php echo $src[0]; ?> ) no-repeat center center ;-webkit-background-size: cover;
	-moz-background-size: cover;
	-o-background-size: cover;
	background-size: cover;"></div>
<div class="overlay"></div>
</div>

8. Adding Post Formats and Create Custom Templates

Post Formats have become a necessity in WordPress themes especially the blogs. They allow you to choose between multiple formats and display content differently based on those formats. First we need to register the formats, we do this by pasting this snippet into the functions.php file.

// Post Formats

add_theme_support( 'post-formats', array( 'gallery', 'image', 'video', 'audio' ) );

Next we can add this code snippet into our single.php file to allow us to create custom templates based on which format the user has chosen. with this format the single.php file will look for template files that begin with content and then end with the format, so for example the gallery format would be content-gallery.php, add this snippet to your single.php file.

<?php get_template_part( 'content', get_post_format() ); ?>

9. Custom Failed Login Message

This snippet is good to add to every theme you create as it can help massively with your websites security.

As most WordPress developers know if WordPress recognizes the username but not the password it will tell you the password is incorrect leaving your site open to hackers who now know your username and can just hit your site trying to login with millions of password variations which is why i also recommend the plugin limit login attempts.

// Change the failed login message for extra WordPress Secruty
function failed_login() {
    return 'Incorrect login information.';
}
add_filter('login_errors', 'failed_login');

So there are my top Wordpres Code snippets, I love building Wordpres themes and would probably be lost without my collection of code snippets. I also use a very helpful site when I am beginning a new theme this site has all of the functions you need to add into your functions.php file to get started visit wpfunction.me and check it out.

If you have any of your own code snippets you'd like to share or have any questions or comments about the ones I've posted let us know in the comments! Send us some of your WordPress Code Snippets and we will add them to our next WordPress Code SNippet Round Up: Add them in the comments or send them to us via the contact form

[info]This isn't something I would normally place on my blog but my family is in need of some help. My uncle needs a double lung transplant and he does not have the money to get it done. My uncle was a huge part of my life growing up and it would be amazing if you could find it in your heart to help him out! They are raising money on a site called Give Forward[/info]

Hi, I'm Josh, I live in a small town near Scranton. I'm a Christian, Husband, Father, Programmer and Nerd. I design and build websites and mobile apps.

  • http://www.wpcustoms.net/ Gerald@WPcustoms

    I grabbed #9 and added it to the archive at http://www.WPcustoms.net – credit link to your site is set – hope you don’t mind :)

    • Web Dev Snippets

      Thank you, glad we could contribute a snippet to your site!

  • http://www.windowsfaralimite.ro/ Cosmin Tataru

    Hi Josh and thanks for your useful articles. I was wondering which sharing plugin you are using. Those buttons look really good. Could you please share that information with us ? Thanks again :D

    • Web Dev Snippets

      Hi Cosmin, thank you for the kind words and the share buttons are custom built into the theme.