Magento Themes , Magento Templates & Wordpress Themes

Magento Themes, Magento Templates, Magento Theme, Magento Template BooThemes.Com 9.5duoc10Rating872 Rating
Useful & Timesaving WordPress Code Snippets
Jan 19, 2011 // Tutorials //

Useful & Timesaving WordPress Code Snippets

Coding in wordpress is pretty state of the art and the code and logic behind the wp theme is much the same. So you can use many source codes and snippets to save your time while coding for wordpress. We are going to share with you some useful wordpress code snippets to save your time and you can design a great wordpress theme with these handy and ready to work code snippets. So build your wordpress plugins or theme with these ready made code snippets.

Show Tag Cloud

The tag cloud function could be used all around the theme: sidebar, footer and everywhere else. It just returns simple links, which can be styled in any way. Wrap the function in div’s or paragraphs to have the desired styling.
[sourcecode language='php']
10, // size of least used tag
‘largest’ => 18, // size of most used tag
‘unit’ => ‘px’, // unit for sizing
‘orderby’ => ‘name’, // alphabetical
‘order’ => ‘ASC’, // starting at A
‘exclude’ => 6 // ID of tag to exclude from list
)); ?>
[/sourcecode]

Shorten The Excerpt

If you think the Excerpt is too long, it’s easy to shorten to a chosen number of words.
[sourcecode language='php']
function new_excerpt_length($length) {
return 20;
}
add_filter(‘excerpt_length’, ‘new_excerpt_length’);
[/sourcecode]

Separate Trackbacks

The trackbacks might be useful function for thanking the bloggers out there spreading your blogpost, but they are kinda ugly. It’s easy to separate them from the comments.
[sourcecode language='php']

  • //Comment code goes here

?>

[/sourcecode]

Share Via Email Link

A simple link that opens users default email client to send an email to a friend or colleague.
[sourcecode language='php']
<?php echo "<a href="mailto:type%20email%20address%20here?subject=I%20wanted%20to
%20share%20this%20post%20with%20you%20from%20
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;body= – ”
title=”Email to a friend/colleague”target=”_blank”>Share via Email“; ?>
[/sourcecode]

List Random Posts

You can display a random post on your blog to make sure none of them are buried and forgotten. Just add the following where you want to show it.
[sourcecode language='php']

  • A random selection of my writing

    • <a href="”>

[/sourcecode]

Paypal Donation Shortcode

This code will make it simpler to accept paypal donations.
[sourcecode language='php']
‘your-paypal-email-address’,
‘for’ => $post->post_title,
‘onHover’ => ”,
), $atts));

if(empty($content)) $content=’Make A Donation’;
return ‘‘.$content.’‘;
}
add_shortcode(‘donate’, ‘donate_shortcode’);
?>
[/sourcecode]

Include Any File

This snippet let’s you include any file you want to without having to print out the whole url yourself. Add this where you want to include the file.
[sourcecode language='php']
get_template_part( ‘filename’ );
[/sourcecode]

List Amount of Post Revisions

WordPress has a great revisioning system that auto-saves your post as you’re working with it. It also allows you to save different drafts and go back to an older one if you want to. Although this is great, the number of revisions often gets carried away, which takes up some database space.

You can easily limit the number of revisions allowed by adding this to wp-config.php:
[sourcecode language='php']
# Maximum 5 revisions #
define(‘WP_POST_REVISIONS’, 5);
# Disable revisions #
define(‘WP_POST_REVISIONS’, false);
[/sourcecode]

Image Custom Field

An easy way to call the a custom field for an image source. Includes IF statement to check if custom field is true.
[sourcecode language='php']
ID, ‘image’, TRUE); ?>
<img src="” alt=”Alt Text” />
[/sourcecode]

Highlight Author Comment

So you want your comments to look different that the readers? No problem. Find the list-item where the comment content is located (usually in comments.php) and add the following in the class-tag:
[sourcecode language='php']
if (1 == $comment->user_id)
echo ‘author’;
[/sourcecode]

Get Post Category Name – ID

This gives you a way to display the current post’s Category ID and / or Category name. I needed this just for debugging and coding purposes but maybe someone can use it.
[sourcecode language='php']
cat_ID;
$catname =$category->cat_name;
echo $postcat;
echo $catname;
}
?>
[/sourcecode]

Enable a Specific Custom Field

Enable a custom field of a specific key (custom field name). Just replace the text in the quotes with your custom field name.
[sourcecode language='php']
ID, ‘insert name here’, true); ?>
[/sourcecode]

Edit Navigation Output

This snippet gives you finer control of the output of WordPress navigation menus

Place the snippet in your themes function file and modify the PHP to get the output you want. For example in WordPress 3.0 in the Menu Builder you can add title’s to menu items. Customizing this output I was able to pass the title into the class for more specific CSS customization.
[sourcecode language='php']
class description_walker extends Walker_Nav_Menu
{
function start_el(&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;$output, $item, $depth, $args)
{
global $wp_query;
$indent = ( $depth ) ? str_repeat( “t”, $depth ) : ”;
$class_names = $value = ”;
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = join( ‘ ‘, apply_filters( ‘nav_menu_css_class’, array_filter( $classes ), $item ) );
$class_names = ‘ class=”‘. esc_attr( $class_names );
$class_names .= ! empty( $item->attr_title ) ? ‘ ‘ . esc_attr( $item->attr_title ) .’”‘ : ‘”‘;
$output .= $indent . ‘

  • ID . ‘”‘ . $value . $class_names .’>’;
    $attributes = ! empty( $item->attr_title ) ? ‘ title=”‘ . esc_attr( $item->attr_title ) .’”‘ : ”;
    $attributes .= ! empty( $item->target ) ? ‘ target=”‘ . esc_attr( $item->target ) .’”‘ : ”;
    $attributes .= ! empty( $item->xfn ) ? ‘ rel=”‘ . esc_attr( $item->xfn ) .’”‘ : ”;
    $attributes .= ! empty( $item->url ) ? ‘ href=”‘ . esc_attr( $item->url ) .’”‘ : ”;
    if($depth != 0)
    {
    $description = $append = $prepend = “”;
    }
    $item_output = $args->before;
    $item_output .= ‘‘;
    $item_output .= $args->link_before .$prepend.apply_filters( ‘the_title’, $item->title, $item->ID ).$append;
    $item_output .= $description.$args->link_after;
    $item_output .= ‘
    ‘;
    $item_output .= $args->after;
    $output .= apply_filters( ‘walker_nav_menu_start_el’, $item_output, $item, $depth, $args );
    }
    }
    [/sourcecode]

    Empty Trash Automatically

    If you want the posts & pages trash to empty automatically, just add this to the wp-config.php-file. The number displayed in the function is the number of days between the emptying.
    [sourcecode language='php']
    define(‘EMPTY_TRASH_DAYS’, 5 );
    [/sourcecode]

    Display Number of Facebook Fans

    If you want to display the number of your Facebook Fans then use this Code. Replace “YOUR PAGE-ID” with your own Page-ID.
    [sourcecode language='php']
    page->fan_count;
    echo $fans;
    ?>
    [/sourcecode]

    Display Search Terms From Google Users

    If a visitor reached your site through Google’s search, this script will display the terms they searched for in order to find your site. Just paste it anywhere outside of the header section.
    [sourcecode language='php']

    [/sourcecode]

    Detect Twitter Users

    If you want to get all the visitors from Twitter a special greeting, add the following to your WordPress blog.
    [sourcecode language='php']
    if (strpos($_SERVER[HTTP_REFERER], “twitter.com”) == true) {
    echo “Hello Twitter User!”;
    }
    [/sourcecode]

    Detect Browser

    If you are using different stylesheets for different browsers theres a different way of detecting the users browsers than the HTML conditional-tags.
    [sourcecode language='php']

    add_filter(‘body_class’,'browser_body_class’);
    function browser_body_class($classes) {
    global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

    if($is_lynx) $classes[] = ‘lynx’;
    elseif($is_gecko) $classes[] = ‘gecko’;
    elseif($is_opera) $classes[] = ‘opera’;
    elseif($is_NS4) $classes[] = ‘ns4′;
    elseif($is_safari) $classes[] = ‘safari’;
    elseif($is_chrome) $classes[] = ‘chrome’;
    elseif($is_IE) $classes[] = ‘ie’;
    else $classes[] = ‘unknown’;

    if($is_iphone) $classes[] = ‘iphone’;
    return $classes;
    }
    [/sourcecode]

    Custom Page Style

    If you want to make a certain page look different from the rest, you can create a custom page for it. Just add a new php-file to your template folder and add the following in the top of it.

    To select it, check the meta-box in the pages-page, located under the tag-box. You can have as many custom pages as you want to.
    [sourcecode language='php']

    /* Template name: Custom Page Name */
    /* Describe the custom page here! */

    get_header();

    # The loop n’ all! #

    the_sidebar();
    get_footer();
    [/sourcecode]

    Custom Display of Links (Blogroll)

    I didn’t like the way my links came out with wplistbookmarks or any other built-in function, so I needed a way to have total control about the way my wordpress bookmarks were displayed. In this example I wanted a table with the Bookmark-image in the left column and title and description in the right column.

    This should probably go into a separate page template but should basically work anywhere in your theme.
    [sourcecode language='php']

    get_results(“SELECT * FROM $wpdb->links ORDER BY link_name ASC”);

    //start the table
    echo “

    “;
    //start going through all the links and get the required values for each link
    foreach ($links as $link) {
    $linkurl=$link->link_url;
    $linkdesc=$link->link_description;
    $linkname=$link->link_name;
    $linkimage=$link->link_image;
    $linknotes=$link->link_notes;

    //write a table row for each link with the link image in the left cell and name and description in right cell
    echo “

    “;
    echo “

    “;
    }
    //finish going through all the links
    echo “

    $linkurl

    “;
    //close the table
    ?>
    [/sourcecode]

    Adding Recent Comments

    A great code snippet you can use to display recent comments in a useful format.
    [sourcecode language='php']

    Recent Comments

    comments
    LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID =
    $wpdb->posts.ID)
    WHERE comment_approved = ’1′ AND comment_type = ” AND
    post_password = ”
    ORDER BY comment_date_gmt DESC
    LIMIT 10″;
    $comments = $wpdb->get_results($sql);
    $output = $pre_HTML;
    $output .= “n

    “;
    $output .= $post_HTML;
    echo $output;?>
    [/sourcecode]

    Change Footer Text in WP Admin

    Change the text in the bottom of the WP admin pages.
    [sourcecode language='php']

    function remove_footer_admin () {
    echo ‘My footer text. Thank you WordPress for giving me this filter.’;
    }
    add_filter(‘admin_footer_text’, ‘remove_footer_admin’);
    [/sourcecode]

    Thumbnail Source

    This snippet gives you the ability to extract the source of the thumbnail image!

    This could be handy if you actually need to do something with the source. It could be needed in any particular situation, where the_post_thumbnail is out of place, which also adds the img tag. The following code creates a variable $image_url which you can use wherever in the document!
    [sourcecode language='php']

    [/sourcecode]

    List Subpages & Siblings

    This is kind of a section navigation. It displays the current page’s subpages and siblings, if there are any. Should work anywhere in your theme.
    [sourcecode language='php']

    post->post_parent) )
    {
    $parent = $wp_query->post->ID;
    }
    else
    {
    $parent = $wp_query->post->post_parent;
    } ?>

    [/sourcecode]

  • 19 Comments on "Useful & Timesaving WordPress Code Snippets"

    1. Wow! Nice collection of snippets, thanks

    2. Eko Setiawan says:

      Very useful snippets, thanks for share

    3. Oliver says:

      With the “Display Search Terms From Google Users” Code you add a nice XSS problem to your blog. First, you do not check if it is really from google, second, you can insert every code.

      Try this referer
      http://attackingpage.com/google/?q=alert('0wned‘)

    4. very useful snippets thanks!

    5. Ashraf says:

      Nice, comprehensive list! Thanks!

    6. Thanks sharing your talent & useful post…..

    7. Aaron says:

      Great list! Learned a little bit more about WordPress so thanks!

    8. espacoevangelico says:

      Parabéns, otimo post. Muito util.

    9. These are really helpful snippets! Thank you.

    Trackbacks for this post

    1. wp-popular.com » Blog Archive » Useful & Timesaving Wordpress Code Snippets | Lava360
    2. Internet Brain » Blog Archive » Bookmarks for January 21st from 22:00 to 22:00
    3. Useful & Timesaving WordPress Code Snippets | WebDevKungfu
    4. WordPress. Le guide definitive agli Hacks e ai Tutorial — Studio404 Web Agency
    5. Found Friday Vol 41 | Paper Leaf Design | Edmonton Graphic Design & Web Design
    6. Shun the Plugin: 100 WordPress Code Snippets from Across the Net | WordPress, Multisite and BuddyPress plugins, themes, news and help – WPMU.org
    7. SFCite | Blog | Shun the Plugin: 100 WordPress Code Snippets from Across the Net
    8. Useful & Timesaving Wordpress Code Snippets | Lava360 | Claudia Troßmann & her daily Snippets
    9. WordPress: The Best of 2011 and Future Predictions | Wptuts+
    10. Wordpress News - The Best WordPress Tips and Tutorials of 2011Wordpress News

    Got something to say? Go for it!

    You must be logged in to post a comment.