code snippets

In many cases, it's better to use a code snippet (or WordPress function) for specific functions than a plugin--if only to have one less item to worry about when updates come around. And while you'll find an endless source of code snippets out there, here are the five we've found to be the most useful when developing for WordPress. Enjoy!

1. Menu display

<?php wp_nav_menu( array( 'menu' => 'Name of Menu' ) ); ?>

As we usually create and name the menus from the back-end, this function allows us to display the menu output on the front end. Of course, you'll need to change "Name of Menu" with the actual name of the menu. Although technically this is a default WordPress function, it has still been too useful to overlook.

Further reading can be found at the WordPress Codex.

2. Remove WordPress Version

This useful snippet will hide the version of WordPress which you're using, making it harder for your site to get hacked (especially if you have outdated versions you're running for side projects).

<?php 
// Remove the WP version for extra WordPress Security 
function remove_wp_version(){ return ''; } 
add_filter('the_generator', 'remove_wp_version'); 
?> 

3. Get featured image source

To retrieve featured image sources, this snippet is useful:


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

You can find more about it over at the WordPress Codex.

4. Custom field value

Custom fields are invaluable when it comes to customizing templates and will allow you to set up custom post types.

<?php echo get_post_meta($post->ID, 'custom-field-key', true); ?> 

5. Limit search to specific post types

Need to exclude certain posts from a search? Adding this to your functions.php file is a quick way to do so.


<?php 
function SearchFilter($query) { 
if ($query->is_search) { 
$query->set('post_type',array('post','page')); 
} 
return $query; 
} 

add_filter('pre_get_posts','SearchFilter'); 
?>

Know of another highly useful WordPress snippet? Let us know in the comments!