Return to Snippet

Revision: 48378
at June 30, 2011 02:09 by sdellow


Initial Code
<h2>Automatically Add Twitter and Facebook Buttons to Your Posts</h2><p>This snippet will add Twitter and Facebook buttons to the bottom of all your posts. All you have to do is paste the code below into your <code>functions.php</code> file:</p><pre class="brush: php; title: ;" title=""> 
function share_this($content){
    if(!is_feed() &amp;&amp; !is_home()) {
        $content .= '&lt;div class=&quot;share-this&quot;&gt;
                    &lt;a href=&quot;http://twitter.com/share&quot;
class=&quot;twitter-share-button&quot;
data-count=&quot;horizontal&quot;&gt;Tweet&lt;/a&gt;
                    &lt;script type=&quot;text/javascript&quot;
src=&quot;http://platform.twitter.com/widgets.js&quot;&gt;&lt;/script&gt;
                    &lt;div class=&quot;facebook-share-button&quot;&gt;
                        &lt;iframe
src=&quot;http://www.facebook.com/plugins/like.php?href='.
urlencode(get_permalink($post-&gt;ID))
.'&amp;amp;layout=button_count&amp;amp;show_faces=false&amp;amp;width=200&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=21&quot;
scrolling=&quot;no&quot; frameborder=&quot;0&quot; style=&quot;border:none;
overflow:hidden; width:200px; height:21px;&quot;
allowTransparency=&quot;true&quot;&gt;&lt;/iframe&gt;
                    &lt;/div&gt;
                &lt;/div&gt;';
    }
    return $content;
}
add_action('the_content', 'share_this');
</pre><p><a href="http://www.wprecipes.com/automatically-add-twitter-and-facebook-buttons-to-your-posts" class="button-med">Source &rarr;</a></p><h2>Track Post View Amount by Using Post Meta</h2><p>For a simple way to keep track of the number of post views, paste this snippet into the <code>functions.php</code>, and then follow steps 1 and 2.</p><pre class="brush: php; title: ;" title=""> 
function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return &quot;0 View&quot;;
    }
    return $count.' Views';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
</pre><p>Step 1: Paste the code below within the <code>single.php</code> within the loop:</p><pre class="brush: php; title: ;" title=""> 
&lt;?php
          setPostViews(get_the_ID());
?&gt;
</pre><p>Step 2: Paste the snippet below anywhere within the template where you would like to display the number of views:</p><pre class="brush: php; title: ;" title=""> 
&lt;?php
          echo getPostViews(get_the_ID());
?&gt;
</pre><p><a href="http://wpsnipp.com/index.php/functions-php/track-post-views-without-a-plugin-using-post-meta/" class="button-med">Source &rarr;</a></p><h2>Track Post View Amount by Using Post Meta</h2><p>This snippet will create a list of your most popular posts based on page views. Please note that this will only work if you have already implemented the &#8216;Track Post View Amount by Using Post Meta&#8217; from above.<br /> Place this snippet just before the loop within the <code>index.php</code> template and WordPress will use the post views to order your posts from highest to lowest.</p><pre class="brush: php; title: ;" title=""> 
&lt;?
query_posts('meta_key=post_views_count&amp;orderby=post_views_count&amp;order=DESC');
?&gt;
</pre><p><a href="http://wpsnipp.com/index.php/loop/most-popular-posts-using-views-post-meta/" class="button-med">Source &rarr;</a></p><h2>Breadcrumbs Without a Plugin</h2><p>Breadcrumbs can be a useful navigation technique that offers link to the previous page the user navigated through to arrive at the current post/page. There are plugins you could use, but the code snippet below could be an easier solution.</p><p>Paste this code into your <code>functions.php</code> file.</p><pre class="brush: php; title: ;" title=""> 
function the_breadcrumb() {
echo '&lt;ul id=&quot;crumbs&quot;&gt;';
if (!is_home()) {
echo '&lt;li&gt;&lt;a href=&quot;';
echo get_option('home');
echo '&quot;&gt;';
echo 'Home';
echo &quot;&lt;/a&gt;&lt;/li&gt;&quot;;
if (is_category() || is_single()) {
echo '&lt;li&gt;';
the_category(' &lt;/li&gt;&lt;li&gt; ');
if (is_single()) {
echo &quot;&lt;/li&gt;&lt;li&gt;&quot;;
the_title();
echo '&lt;/li&gt;';
}
} elseif (is_page()) {
echo '&lt;li&gt;';
echo the_title();
echo '&lt;/li&gt;';
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo&quot;&lt;li&gt;Archive for &quot;; the_time('F jS, Y'); echo'&lt;/li&gt;';}
elseif (is_month()) {echo&quot;&lt;li&gt;Archive for &quot;; the_time('F, Y'); echo'&lt;/li&gt;';}
elseif (is_year()) {echo&quot;&lt;li&gt;Archive for &quot;; the_time('Y'); echo'&lt;/li&gt;';}
elseif (is_author()) {echo&quot;&lt;li&gt;Author Archive&quot;; echo'&lt;/li&gt;';}
elseif (isset($_GET['paged']) &amp;&amp; !empty($_GET['paged'])) {echo &quot;&lt;li&gt;Blog Archives&quot;; echo'&lt;/li&gt;';}
elseif (is_search()) {echo&quot;&lt;li&gt;Search Results&quot;; echo'&lt;/li&gt;';}
echo '&lt;/ul&gt;';
}</pre><p>Then paste the calling code below, wherever you would like the breadcrumbs to appear (typically above the title tag).</p><pre class="brush: php; title: ;" title="">&lt;?php the_breadcrumb(); ?&gt;</pre><p><a href="http://wp-snippets.com/breadcrumbs-without-plugin/" class="button-med">Source &rarr;</a></p><h2>Display the Number of Facebook Fans</h2><p>Facebook is a must site for sharing your blogs articles. Here is a method for showing your visitors the total number of Facebook &#8216;Likes&#8217; your blog currently has.</p><p>To use this code all you have to do is replace the <strong>YOUR PAGE-ID</strong> with your own Facebook page id.</p><pre class="brush: php; title: ;" title="">&lt;?php
$page_id = &quot;YOUR PAGE-ID&quot;;
$xml = @simplexml_load_file(&quot;http://api.facebook.com/restserver.php?method=facebook.fql.query&amp;query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=&quot;.$page_id.&quot;&quot;) or die (&quot;a lot&quot;);
$fans = $xml-&gt;page-&gt;fan_count;
echo $fans;
?&gt;</pre><p><a href="http://wp-snippets.com/display-number-facebook-fans/" class="button-med">Source &rarr;</a></p><h2>Display an External RSS Feed</h2><p>This snippet will fetch the latest entries of any specified feed url.</p><pre class="brush: php; title: ;" title="">&lt;?php include_once(ABSPATH.WPINC.'/rss.php');
wp_rss('http://wpforums.com/external.php?type=RSS2', 5); ?&gt;</pre><p>This code takes the rss.php file that is built into WordPress (used for widgets). It is set to display the most recent 5 posts from the RSS feed &#8216;http://example.com/external.php?type=RSS2&#8242;.</p><p><a href="http://wphacks.com/how-to-adding-an-external-rss-feed-to-your-wordpress-blog/" class="button-med">Source &rarr;</a></p><h2>WP Shortcode to Display External Files</h2><p>If you are looking for a quick way to automatically include external page content within your post, this snippet will create a shortcode allowing you to do it.</p><p>Paste this code into your themes <code>functions.php</code> file:</p><pre class="brush: php; title: ;" title=""> 
function show_file_func( $atts ) {
  extract( shortcode_atts( array(
    'file' =&gt; ''
  ), $atts ) );
 
  if ($file!='')
    return @file_get_contents($file);
}
 
add_shortcode( 'show_file', 'show_file_func' );
</pre><p>And then post this shortcode, editing the URL, into your post or page.</p><pre class="brush: php; title: ;" title=""> 
[show_file file=&quot;http://speckyboy.com/2010/12/09/20-plugin-replacing-tutorials-tips-snippets-and-solutions-for-wordpress/&quot;]
</pre><p><a href="http://www.prelovac.com/vladimir/wordpress-shortcode-snippet-to-display-external-files" class="button-med">Source &rarr;</a></p><h2>Create Custom Widgets</h2><p><img src="http://speckyboy.com/wp-content/uploads/2011/03/wp_snippet_06.jpg" alt="Create Custom Widgets"><br /> Wordpress provides many widgets, but if you want to create custom widgets tailored to your blog, then this snippet may help you.</p><p>Paste the code below into your <code>functions.php</code> file.</p><pre class="brush: php; title: ;" title="">    class My_Widget extends WP_Widget {
        function My_Widget() {
            parent::WP_Widget(false, 'Our Test Widget');
        }
    function form($instance) {
            // outputs the options form on admin
        }
    function update($new_instance, $old_instance) {
            // processes widget options to be saved
            return $new_instance;
        }
    function widget($args, $instance) {
            // outputs the content of the widget
        }
    }
    register_widget('My_Widget');
	</pre><p><a href="http://www.darrenhoyt.com/2009/12/22/creating-custom-wordpress-widgets/" class="button-med">Source &rarr;</a></p><h2>Create Custom Shortcodes</h2><p>Shortcodes are a handy way of using code functions within your theme. The advantage of shortcodes is that they can be easily used with the WordPress  post editor.</p><p>Add this code to your <code>functions.php</code>:</p><pre class="brush: php; title: ;" title="">function helloworld() {
return 'Hello World!';
}
add_shortcode('hello', 'helloworld');</pre><p>You can then use [hello] wherever you want to display the content of the shortcode.</p><p><a href="http://wp-snippets.com/add-shortcodes/" class="button-med">Source &rarr;</a></p><h2>Custom Title Length</h2><p>This snippet will allow you to customise the length (by the number of characters) of your post title.</p><p>Paste this code into the <code>functions.php</code>:</p><pre class="brush: php; title: ;" title=""> 
function ODD_title($char)
    {
    $title = get_the_title($post-&gt;ID);
    $title = substr($title,0,$char);
    echo $title;
    }</pre><p>To use this function all you have to do is paste the below code into your theme files, remembering to change the &#8217;20&#8242; to what ever character amount you require:</p><pre class="brush: php; title: ;" title=""> 
&lt;?php ODD_title(20); ?&gt;
</pre><p><a href="http://www.orangedevdesign.nl/nieuws/wordpress-title-custom-length/" class="button-med">Source &rarr;</a></p><h2>Custom Excerpts</h2><p>Sometimes you may need to limit how many words are in the excerpt, with this snippet you can create your own custom excerpt (my_excerpts) replacing the original.</p><p>Paste this code in <code>functions.php</code>.</p><pre class="brush: php; title: ;" title=""> 
&lt;?php add_filter('the_excerpt', 'my_excerpts');
function my_excerpts($content = false) {
            global $post;
            $mycontent = $post-&gt;post_excerpt;
 
            $mycontent = $post-&gt;post_content;
            $mycontent = strip_shortcodes($mycontent);
            $mycontent = str_replace(']]&gt;', ']]&amp;gt;', $mycontent);
            $mycontent = strip_tags($mycontent);
            $excerpt_length = 55;
            $words = explode(' ', $mycontent, $excerpt_length + 1);
            if(count($words) &gt; $excerpt_length) :
                array_pop($words);
                array_push($words, '...');
                $mycontent = implode(' ', $words);
            endif;
            $mycontent = '&lt;p&gt;' . $mycontent . '&lt;/p&gt;';
// Make sure to return the content
    return $mycontent;
}
?&gt;</pre><p>Secondly, paste this code within the Loop:</p><pre class="brush: php; title: ;" title=""> 
&lt;?php echo my_excerpts(); ?&gt;
</pre><p><a href="http://wptricks.net/create-you-own-excerpt-in-wordpress/" class="button-med">Source &rarr;</a></p><h2>Redirect Your Post Titles To External Links</h2><p><img src="http://speckyboy.specky.netdna-cdn.com/wp-content/uploads/2011/03/wp_snippet_01.jpg" alt="Redirect Your Post Titles To External Links"><br /> This snippet could be useful for anyone with a news submission site, by redirecting your post title to an external URL when clicked via a custom field.</p><p>Paste this snippet into your <code>functions.php</code> file:</p><pre class="brush: php; title: ;" title="">//Custom Redirection
function print_post_title() {
global $post;
$thePostID = $post-&gt;ID;
$post_id = get_post($thePostID);
$title = $post_id-&gt;post_title;
$perm  = get_permalink($post_id);
$post_keys = array(); $post_val  = array();
$post_keys = get_post_custom_keys($thePostID);
if (!empty($post_keys)) {
foreach ($post_keys as $pkey) {
if ($pkey=='url') {
$post_val = get_post_custom_values($pkey);
}
}
if (empty($post_val)) {
$link = $perm;
} else {
$link = $post_val[0];
}
} else {
$link = $perm;
}
echo '&lt;h2&gt;&lt;a href=&quot;'.$link.'&quot; rel=&quot;bookmark&quot; title=&quot;'.$title.'&quot;&gt;'.$title.'&lt;/a&gt;&lt;/h2&gt;';
}</pre><p>Then you add a custom field named &#8216;url&#8217; and in the value field put the link to which the title is to be redirected to.</p><p><a href="http://www.wprecipes.com/how-to-link-to-some-external-ressource-in-post-title" class="button-med">Source &rarr;</a></p><h2>Redirect to Single Post If There is One Post in Category/Tag</h2><p>If there is only one post within a category or tag, this little snippet will jump the reader directly to the post page.</p><p>Paste this code into your themes <code>functions.php</code> file:</p><pre class="brush: php; title: ;" title=""> 
function stf_redirect_to_post(){
    global $wp_query;
 
    // If there is one post on archive page
    if( is_archive() &amp;&amp; $wp_query-&gt;post_count == 1 ){
        // Setup post data
        the_post();
        // Get permalink
        $post_url = get_permalink();
        // Redirect to post page
        wp_redirect( $post_url );
    }  
 
} add_action('template_redirect', 'stf_redirect_to_post');
</pre><p><a href="http://shailan.com/how-to-redirect-to-single-post-page-if-there-is-one-post-in-categorytag/" class="button-med">Source &rarr;</a></p><h2>List Scheduled/Future Posts</h2><p>Paste the code anywhere on your template where you want your scheduled posts to be listed, changing the max number or displayed posts by changing the value of showposts in the query.</p><pre class="brush: php; title: ;" title=""> 
&lt;?php
$my_query = new WP_Query('post_status=future&amp;order=DESC&amp;showposts=5');
if ($my_query-&gt;have_posts()) {
    while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post();
        $do_not_duplicate = $post-&gt;ID; ?&gt;
        &lt;li&gt;&lt;?php the_title(); ?&gt;&lt;/li&gt;
    &lt;?php endwhile;
}
?&gt;
</pre><p><a href="http://www.wprecipes.com/how-to-list-scheduled-posts" class="button-med">Source &rarr;</a></p><h2>Screenshots of External Pages Without a Plugin</h2><p>This is a very simple URL script that will generate a screenshot of any website. Here is the URL:</p><pre class="brush: xml; title: ;" title="">http://s.wordpress.com/mshots/v1/http%3A%2F%2Fspeckyboy.com%2F?w=500</pre><p>To see what the link above does, <a href="http://s.wordpress.com/mshots/v1/http%3A%2F%2Fspeckyboy.com%2F?w=500" target="_blank">click here</a>.</p><p>All you have to do is insert your required URL in the place of the &#8216;speckyboy.com&#8217; part of the link and resize (&#8216;w=500&#8242;) as required.</p><h2>Add Content to the End of Each RSS Post</h2><p>Adding some extra content that is only viewable by your RSS subscribers couldn&#8217;t be easier with this snippet.<br /> Paste this code into the functions.php:</p><pre class="brush: php; title: ;" title=""> 
function feedFilter($query) {
    if ($query-&gt;is_feed) {
        add_filter('the_content','feedContentFilter');
    }
    return $query;
}
add_filter('pre_get_posts','feedFilter');
 
function feedContentFilter($content) {
    $content .= '&lt;p&gt;Extra RSS content goes here... &lt;/p&gt;';
 
    return $content;
}
</pre><p><a href="http://wptricks.net/how-to-add-content-to-the-end-of-each-rss-post/" class="button-med">Source &rarr;</a></p><h2>Reset Your WordPress Password</h2><p><img src="http://speckyboy.specky.netdna-cdn.com/wp-content/uploads/2011/03/wp_snippet_02.jpg" alt="Redirect Your Post Titles To External Links"></p><p>What would you do if you forget your WordPress Admin Password and you no longer have access to the admin area? To fix this all you have to do is jump to your PhpMyAdmin Sql-window and run the following command.</p><pre class="brush: sql; title: ;" title="">UPDATE `wp_users` SET `user_pass` = MD5('NEW_PASSWORD') WHERE `wp_users`.`user_login` =`YOUR_USER_NAME` LIMIT 1;</pre><p><a href="http://wp-snippets.com/reset-your-password/" class="button-med">Source &rarr;</a></p><h2>Detect Which Browser Your Visitors are Using</h2><p>If you want to use different stylesheets for different browsers, then this is a snippet you could use. It detects the browser your visitors are using and creates a different class for each browser. You can use that class to create custom stylesheets.</p><pre class="brush: php; title: ;" title="">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;
}</pre><p><a href="http://www.nathanrice.net/blog/browser-detection-and-the-body_class-function/" class="button-med">Source &rarr;</a></p><h2>Display Search Terms from Google Users</h2><p>If a visitor reached your site through Google&#8217;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.</p><pre class="brush: php; title: ;" title=""> 
&lt;?php
$refer = $_SERVER[&quot;HTTP_REFERER&quot;];
if (strpos($refer, &quot;google&quot;)) {
        $refer_string = parse_url($refer, PHP_URL_QUERY);
        parse_str($refer_string, $vars);
        $search_terms = $vars['q'];
        echo 'Welcome Google visitor! You searched for the following terms to get here: ';
        echo $search_terms;
};
?&gt;
</pre><p><a href="http://wp-snippets.com/display-search-terms-from-google-users/" class="button-med">Source &rarr;</a></p><h2>Show Different Content for Mac &amp; Windows</h2><p>If you ever have the need to display different content to either Mac or Windows users (ie. software download link for different platforms), you can paste the following code into your themes <code>functions.php</code> file. You can easily change the content of the function to your own needs.</p><pre class="brush: php; title: ;" title="">&lt;?php
if (stristr($_SERVER['HTTP_USER_AGENT'],&quot;mac&quot;)) {
echo ‘Hello, I\’m a Mac.’;
} else {
echo ‘And I\’m a PC.’;
}
?&gt;</pre>

Initial URL

                                

Initial Description
Snippets for Wordpress functions

Initial Title
Wordpress Code Snippets

Initial Tags
wordpress

Initial Language
HTML