Posted By

sdellow on 06/30/11


Tagged

wordpress


Versions (?)

Wordpress Code Snippets


 / Published in: HTML
 

Snippets for Wordpress functions

  1. <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="">
  2. function share_this($content){
  3. if(!is_feed() &amp;&amp; !is_home()) {
  4. $content .= '&lt;div class=&quot;share-this&quot;&gt;
  5. &lt;a href=&quot;http://twitter.com/share&quot;
  6. class=&quot;twitter-share-button&quot;
  7. data-count=&quot;horizontal&quot;&gt;Tweet&lt;/a&gt;
  8. &lt;script type=&quot;text/javascript&quot;
  9. src=&quot;http://platform.twitter.com/widgets.js&quot;&gt;&lt;/script&gt;
  10. &lt;div class=&quot;facebook-share-button&quot;&gt;
  11. &lt;iframe
  12. src=&quot;http://www.facebook.com/plugins/like.php?href='.
  13. urlencode(get_permalink($post-&gt;ID))
  14. .'&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;
  15. scrolling=&quot;no&quot; frameborder=&quot;0&quot; style=&quot;border:none;
  16. overflow:hidden; width:200px; height:21px;&quot;
  17. allowTransparency=&quot;true&quot;&gt;&lt;/iframe&gt;
  18. &lt;/div&gt;
  19. &lt;/div&gt;';
  20. }
  21. return $content;
  22. }
  23. add_action('the_content', 'share_this');
  24. </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="">
  25. function getPostViews($postID){
  26. $count_key = 'post_views_count';
  27. $count = get_post_meta($postID, $count_key, true);
  28. if($count==''){
  29. delete_post_meta($postID, $count_key);
  30. add_post_meta($postID, $count_key, '0');
  31. return &quot;0 View&quot;;
  32. }
  33. return $count.' Views';
  34. }
  35. function setPostViews($postID) {
  36. $count_key = 'post_views_count';
  37. $count = get_post_meta($postID, $count_key, true);
  38. if($count==''){
  39. $count = 0;
  40. delete_post_meta($postID, $count_key);
  41. add_post_meta($postID, $count_key, '0');
  42. }else{
  43. $count++;
  44. update_post_meta($postID, $count_key, $count);
  45. }
  46. }
  47. </pre><p>Step 1: Paste the code below within the <code>single.php</code> within the loop:</p><pre class="brush: php; title: ;" title="">
  48. &lt;?php
  49. setPostViews(get_the_ID());
  50. ?&gt;
  51. </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="">
  52. &lt;?php
  53. echo getPostViews(get_the_ID());
  54. ?&gt;
  55. </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="">
  56. &lt;?
  57. query_posts('meta_key=post_views_count&amp;orderby=post_views_count&amp;order=DESC');
  58. ?&gt;
  59. </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="">
  60. function the_breadcrumb() {
  61. echo '&lt;ul id=&quot;crumbs&quot;&gt;';
  62. if (!is_home()) {
  63. echo '&lt;li&gt;&lt;a href=&quot;';
  64. echo get_option('home');
  65. echo '&quot;&gt;';
  66. echo 'Home';
  67. echo &quot;&lt;/a&gt;&lt;/li&gt;&quot;;
  68. if (is_category() || is_single()) {
  69. echo '&lt;li&gt;';
  70. the_category(' &lt;/li&gt;&lt;li&gt; ');
  71. if (is_single()) {
  72. echo &quot;&lt;/li&gt;&lt;li&gt;&quot;;
  73. the_title();
  74. echo '&lt;/li&gt;';
  75. }
  76. } elseif (is_page()) {
  77. echo '&lt;li&gt;';
  78. echo the_title();
  79. echo '&lt;/li&gt;';
  80. }
  81. }
  82. elseif (is_tag()) {single_tag_title();}
  83. elseif (is_day()) {echo&quot;&lt;li&gt;Archive for &quot;; the_time('F jS, Y'); echo'&lt;/li&gt;';}
  84. elseif (is_month()) {echo&quot;&lt;li&gt;Archive for &quot;; the_time('F, Y'); echo'&lt;/li&gt;';}
  85. elseif (is_year()) {echo&quot;&lt;li&gt;Archive for &quot;; the_time('Y'); echo'&lt;/li&gt;';}
  86. elseif (is_author()) {echo&quot;&lt;li&gt;Author Archive&quot;; echo'&lt;/li&gt;';}
  87. elseif (isset($_GET['paged']) &amp;&amp; !empty($_GET['paged'])) {echo &quot;&lt;li&gt;Blog Archives&quot;; echo'&lt;/li&gt;';}
  88. elseif (is_search()) {echo&quot;&lt;li&gt;Search Results&quot;; echo'&lt;/li&gt;';}
  89. echo '&lt;/ul&gt;';
  90. }</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
  91. $page_id = &quot;YOUR PAGE-ID&quot;;
  92. $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;);
  93. $fans = $xml-&gt;page-&gt;fan_count;
  94. echo $fans;
  95. ?&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');
  96. 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="">
  97. function show_file_func( $atts ) {
  98. extract( shortcode_atts( array(
  99. 'file' =&gt; ''
  100. ), $atts ) );
  101.  
  102. if ($file!='')
  103. return @file_get_contents($file);
  104. }
  105.  
  106. add_shortcode( 'show_file', 'show_file_func' );
  107. </pre><p>And then post this shortcode, editing the URL, into your post or page.</p><pre class="brush: php; title: ;" title="">
  108. [show_file file=&quot;http://speckyboy.com/2010/12/09/20-plugin-replacing-tutorials-tips-snippets-and-solutions-for-wordpress/&quot;]
  109. </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 {
  110. function My_Widget() {
  111. parent::WP_Widget(false, 'Our Test Widget');
  112. }
  113. function form($instance) {
  114. // outputs the options form on admin
  115. }
  116. function update($new_instance, $old_instance) {
  117. // processes widget options to be saved
  118. return $new_instance;
  119. }
  120. function widget($args, $instance) {
  121. // outputs the content of the widget
  122. }
  123. }
  124. register_widget('My_Widget');
  125. </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() {
  126. return 'Hello World!';
  127. }
  128. 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="">
  129. function ODD_title($char)
  130. {
  131. $title = get_the_title($post-&gt;ID);
  132. $title = substr($title,0,$char);
  133. echo $title;
  134. }</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="">
  135. &lt;?php ODD_title(20); ?&gt;
  136. </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="">
  137. &lt;?php add_filter('the_excerpt', 'my_excerpts');
  138. function my_excerpts($content = false) {
  139. global $post;
  140. $mycontent = $post-&gt;post_excerpt;
  141.  
  142. $mycontent = $post-&gt;post_content;
  143. $mycontent = strip_shortcodes($mycontent);
  144. $mycontent = str_replace(']]&gt;', ']]&amp;gt;', $mycontent);
  145. $mycontent = strip_tags($mycontent);
  146. $excerpt_length = 55;
  147. $words = explode(' ', $mycontent, $excerpt_length + 1);
  148. if(count($words) &gt; $excerpt_length) :
  149. array_pop($words);
  150. array_push($words, '...');
  151. $mycontent = implode(' ', $words);
  152. endif;
  153. $mycontent = '&lt;p&gt;' . $mycontent . '&lt;/p&gt;';
  154. // Make sure to return the content
  155. return $mycontent;
  156. }
  157. ?&gt;</pre><p>Secondly, paste this code within the Loop:</p><pre class="brush: php; title: ;" title="">
  158. &lt;?php echo my_excerpts(); ?&gt;
  159. </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
  160. function print_post_title() {
  161. global $post;
  162. $thePostID = $post-&gt;ID;
  163. $post_id = get_post($thePostID);
  164. $title = $post_id-&gt;post_title;
  165. $perm = get_permalink($post_id);
  166. $post_keys = array(); $post_val = array();
  167. $post_keys = get_post_custom_keys($thePostID);
  168. if (!empty($post_keys)) {
  169. foreach ($post_keys as $pkey) {
  170. if ($pkey=='url') {
  171. $post_val = get_post_custom_values($pkey);
  172. }
  173. }
  174. if (empty($post_val)) {
  175. $link = $perm;
  176. } else {
  177. $link = $post_val[0];
  178. }
  179. } else {
  180. $link = $perm;
  181. }
  182. 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;';
  183. }</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="">
  184. function stf_redirect_to_post(){
  185. global $wp_query;
  186.  
  187. // If there is one post on archive page
  188. if( is_archive() &amp;&amp; $wp_query-&gt;post_count == 1 ){
  189. // Setup post data
  190. the_post();
  191. // Get permalink
  192. $post_url = get_permalink();
  193. // Redirect to post page
  194. wp_redirect( $post_url );
  195. }
  196.  
  197. } add_action('template_redirect', 'stf_redirect_to_post');
  198. </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="">
  199. &lt;?php
  200. $my_query = new WP_Query('post_status=future&amp;order=DESC&amp;showposts=5');
  201. if ($my_query-&gt;have_posts()) {
  202. while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post();
  203. $do_not_duplicate = $post-&gt;ID; ?&gt;
  204. &lt;li&gt;&lt;?php the_title(); ?&gt;&lt;/li&gt;
  205. &lt;?php endwhile;
  206. }
  207. ?&gt;
  208. </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="">
  209. function feedFilter($query) {
  210. if ($query-&gt;is_feed) {
  211. add_filter('the_content','feedContentFilter');
  212. }
  213. return $query;
  214. }
  215. add_filter('pre_get_posts','feedFilter');
  216.  
  217. function feedContentFilter($content) {
  218. $content .= '&lt;p&gt;Extra RSS content goes here... &lt;/p&gt;';
  219.  
  220. return $content;
  221. }
  222. </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');
  223. function browser_body_class($classes) {
  224. global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
  225. if($is_lynx) $classes[] = 'lynx';
  226. elseif($is_gecko) $classes[] = 'gecko';
  227. elseif($is_opera) $classes[] = 'opera';
  228. elseif($is_NS4) $classes[] = 'ns4';
  229. elseif($is_safari) $classes[] = 'safari';
  230. elseif($is_chrome) $classes[] = 'chrome';
  231. elseif($is_IE) $classes[] = 'ie';
  232. else $classes[] = 'unknown';
  233. if($is_iphone) $classes[] = 'iphone';
  234. return $classes;
  235. }</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="">
  236. &lt;?php
  237. $refer = $_SERVER[&quot;HTTP_REFERER&quot;];
  238. if (strpos($refer, &quot;google&quot;)) {
  239. $refer_string = parse_url($refer, PHP_URL_QUERY);
  240. parse_str($refer_string, $vars);
  241. $search_terms = $vars['q'];
  242. echo 'Welcome Google visitor! You searched for the following terms to get here: ';
  243. echo $search_terms;
  244. };
  245. ?&gt;
  246. </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
  247. if (stristr($_SERVER['HTTP_USER_AGENT'],&quot;mac&quot;)) {
  248. echo ‘Hello, I\’m a Mac.’;
  249. } else {
  250. echo ‘And I\’m a PC.’;
  251. }
  252. ?&gt;</pre>

Report this snippet  

You need to login to post a comment.