essential WordPress snippets

Essential WordPress Snippets

As much as we’d like to think that every WordPress theme should come with a specific set of features, it usually doesn’t. What happens when your theme doesn’t have a feature you want? You just drop it in yourself, using these .

Template Directory

<?php bloginfo('template_directory'); ?>
Use this snippet to automatically go though the entire file path of your WordPress theme. This is essential for linking to files and images within your theme. You wouldn’t want to have to type out the entire file path every time. This would be insane.

The Permalink

<?php the_permalink(); ?>
This is used to get the link to the post or page. This is essential for linking to a full post from a title or a read more button on a blog page. This is also used on other pages such as archive pages. It basically links to the post itself, based on your permalink structure.

Include (in WordPress)

<?php include (TEMPLATEPATH . '/filename.php'); ?>
This makes it so that you can include custom PHP files in your themes. This makes it so that WordPress will include xxx.php in your theme, enabling custom functionality without muddying up the core theme.

Dynamic Sidebars

WordPress makes it easy to drop a sidebar wherever you want. This makes it super-easy to customize your theme and add widgets wherever you want them. To enable a sidebar, you have to register in it your functions.php file.

<?php if(!function_exists('dynamic_sidebar') || !dynamic_sidebar('Sidebar') ) : ?><?php endif; ?>
Then in your theme place the following where you want a sidebar.
<?php
if (function_exists('register_sidebar') )
    register_sidebar(array(
        'before_widget' => '<div>',
        'after_widget' => '</div>',
        'before_title' => '<h2>',
        'after_title' => '</h2>',
    ))
;
?>

Include jQuery in Your WordPress Theme

jQuery comes packaged with WordPress, so you don’t have to drop it in again. Here’s how you call upon WordPress in your theme.
 <?php wp_enqueue_script("jquery"); ?>

Add Google Analytics to Your Theme

Google Analytics is important for tracking your stats, visitors, and breaking down traffic. However, having to add the code to your theme each time leaves you wide open to forgetting, causing you to lose track of all your stats. Add this to your functions to avoid this problem in the future.

<?php 

add_action('wp_footer', 'ga'); 
function ga() { ?> 
// Paste your Google Analytics code here
<?php } ?>