30 Extremely Useful WordPress Code Snippets & Hacks
Productivity is a great asset in a business. Once you are productive, you are committing yourself to excellence. That’s what snippets do. Snippets are tools – reusable codes that display specific functions – which can increase your speed in coding. By using snippets, you are able to minimize the use of repeated codes thus time consumed in coding is reduced. Our post for today will definitely help you become more productive in working with the most popular blogging tool over the internet nowadays – wordpress. Here are 30 Extremely Useful WordPress Code Snippets & Hacks. If you know a wordpress snippet link or if you have your own snippet please add it in the comment below. Enjoy!
You may also want to read the related article below.
1. Change ‘Enter Title Here’ Text in WordPress 3.1
Easily change the default title text with a new filter in WordPress 3.1. Copy the this into functions.php
To change the default text, simply create a new function and hook it to the ‘enter_title_here’ filter, such as below:
|
1 2 3 4 5 6 7 8 |
function jk_change_default_title( $title ){ $title = 'My New Title'; return $title; } add_filter( 'enter_title_here', 'jk_change_default_title' ); |
For better control, we can use this to only change the title of specific post types. This is great for custom post types. In this example, we’ll use the custom post type of ‘invoice’.
|
1 2 3 4 5 6 7 8 9 10 11 |
function jk_change_default_title( $title ){ $screen = get_current_screen(); if ( 'invoice' == $screen->post_type ) { $title = 'Enter Invoice Title'; } return $title; } add_filter( 'enter_title_here', 'jk_change_default_title' ); |
Source: http://www.johnkolbert.com/wordpress/change-enter-title-here-text-in-wordpress-3-1/
2. Automatically create thumbnails of sites with WordPress
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
gk_snap function ($ atts, $ content = null) { extract (shortcode_atts (array ( "Snap" => 'http://s.wordpress.com/mshots/v1/' "Url" => 'http://www.geekeries.fr' "Alt" => 'My picture' "W" => '400 ', / / width "H" => '300 '/ / Height ), $ Atts)); $ Img = '<img src = "'. $ Snap.''. Urlencode ($ url).? 'W ='. $ W. '& H ='. $ H. '" Alt = "'. $ Alt. '"/>'; return $ img; } add_shortcode ("snap," "gk_snap"); |
This piece of code is pasted into the file functions.php in your WordPress theme. Subsequently, it is very easy to use in your articles. To do this, you simply paste the custom tag ( shortcode ) by completing the settings. The height is still optional. It is usually calculated using the width. Here’s an example:
|
1 |
[Url = snap "http://www.geekeries.fr/publicites/" alt = "My description" w = "400" h = "300"] |
Source: http://www.geekeries.fr/snippet/creer-automatiquement-miniatures-sites-wordpress/
3. Integrate some Adsense Ads
Want to output some adsense ads in posts? Try this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function adsense_shortcode( $atts ) { extract(shortcode_atts(array( 'format' => '1', ), $atts)); switch ($format) { case 1 : $ad = '<script type="text/javascript"><!-- google_ad_client = "pub-6928386133078955"; /* 234x60, created 16/09/08 */ google_ad_slot = "0834408702"; google_ad_width = 234; google_ad_height = 60; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>'; break; } return $ad; } add_shortcode('adsense', 'adsense_shortcode'); |
Remember to replace the adsense code with your own from google. Now you can output an ad simply using [adsense].
Add additional ad formats to the switch statement and you can output other ad formats using, for example, [adsense format="2"]. Nice eh?
Source: http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress/
4. Show related posts (uses tags)
Add this funciton in your functions.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
function related_posts_shortcode( $atts ) { extract(shortcode_atts(array( 'limit' => '5', ), $atts)); global $wpdb, $post, $table_prefix; if ($post->ID) { $retval = ' <ul>'; // Get tags $tags = wp_get_post_tags($post->ID); $tagsarray = array(); foreach ($tags as $tag) { $tagsarray[] = $tag->term_id; } $tagslist = implode(',', $tagsarray); // Do the query $q = " SELECT p.*, count(tr.object_id) as count FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID AND p.post_status = 'publish' AND p.post_date_gmt < NOW() GROUP BY tr.object_id ORDER BY count DESC, p.post_date_gmt DESC LIMIT $limit;"; $related = $wpdb->get_results($q); if ( $related ) { foreach($related as $r) { $retval .= ' <li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li> '; } } else { $retval .= ' <li>No related posts found</li> '; } $retval .= '</ul> '; return $retval; } return; } add_shortcode('related_posts', 'related_posts_shortcode'); |
I’m using this shortcode on this blog. Now See an example below on how it works.
Source: http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress/
5. Add a simple paypal donation link
Replace the default ‘account’ with your paypal email address, and output using [donate]
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function donate_shortcode( $atts ) { extract(shortcode_atts(array( 'text' => 'Make a donation', 'account' => 'REPLACE ME', 'for' => '', ), $atts)); global $post; if (!$for) $for = str_replace(" ","+",$post->post_title); return '<a class="donateLink" href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation+for+'.$for.'">'.$text.'</a>'; } add_shortcode('donate', 'donate_shortcode'); |
Source: http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress/
6. How to display your latest Google+ update on your WordPress blog
Simply paste the following code where you want to display your latest Google+ update. Don’t forget to put your Google+ ID on line 3.
|
1 2 3 4 5 6 7 8 |
<?php include_once(ABSPATH.WPINC.'/rss.php'); $googleplus = fetch_feed("http://plusfeed.appspot.com/103329092193061943712"); // Replace 103329092193061943712 by your own ID echo '<a href="'; echo $googleplus->items[0]['link']; echo '">'; echo $googleplus->items[0]['summary']; echo ''; ?> |
Source: http://www.wprecipes.com/how-to-display-your-latest-google-update-on-your-wordpress-blog
7. Change Login Logo URL
We can Change the Login Logo from the default WordPress logo to something else, but what if you also want to change the Link that the logo points to, to go from www.wordpress.com to someplace else? There is a different hook for that. Add this to functions.php:
|
1 2 3 4 5 6 |
<?php add_filter( 'login_headerurl', 'my_custom_login_url' ); function my_custom_login_url($url) { return 'http://www.example.com'; } ?> |
Source: http://wp-snippets.com/957/change-login-logo-url/
8. List subpages and 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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php global $wp_query; if( empty($wp_query->post->post_parent) ) { $parent = $wp_query->post->ID; } else { $parent = $wp_query->post->post_parent; } ?> <?php if(wp_list_pages("title_li=&child_of=$parent&echo=0" )): ?> <div id="submenu"> <ul> <?php wp_list_pages("title_li=&child_of=$parent" ); ?> </ul> </div> <?php endif; ?> |
Source: http://wp-snippets.com/736/list-subpages-and-siblings/
9. Pagination without plugin
To implement it, just add this code to functions.php:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function pagination($prev = '«', $next = '»') { global $wp_query, $wp_rewrite; $wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1; $pagination = array( 'base' => @add_query_arg('paged','%#%'), 'format' => '', 'total' => $wp_query->max_num_pages, 'current' => $current, 'prev_text' => __($prev), 'next_text' => __($next), 'type' => 'plain' ); if( $wp_rewrite->using_permalinks() ) $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' ); if( !empty($wp_query->query_vars['s']) ) $pagination['add_args'] = array( 's' => get_query_var( 's' ) ); echo paginate_links( $pagination ); }; |
Now you can add the pagination using the pagination(). function. Add it somewhere outside the loop, but inside the if( have_post() ) statement.
|
1 2 3 4 5 6 7 8 |
<?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> // post goes here <?php endwhile; ?> <div class="pagination"><?php pagination('»', '«'); ?></div> <?php endif; ?> |
Source: http://wp-snippets.com/1896/pagination-without-plugin/
10. Breadcrumbs without plugin
Create a breadcrumb menu by adding this to functions.php:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
function the_breadcrumb() { echo '<ul id="crumbs">'; if (!is_home()) { echo '<li><a href="'; echo get_option('home'); echo '">'; echo 'Home'; echo "</a></li>"; if (is_category() || is_single()) { echo '<li>'; the_category(' </li><li> '); if (is_single()) { echo "</li><li>"; the_title(); echo '</li>'; } } elseif (is_page()) { echo '<li>'; echo the_title(); echo '</li>'; } } elseif (is_tag()) {single_tag_title();} elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';} elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';} elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';} elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';} elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';} elseif (is_search()) {echo"<li>Search Results"; echo'</li>';} echo '</ul>'; } |
To display the menu, just use this function to display it wherever you want:
|
1 |
<?php the_breadcrumb(); ?> |
Source: http://wp-snippets.com/880/breadcrumbs-without-plugin/
11. Display the Number of Comments by Author
Copy the function below into your functions.php:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
function author_comment_count(){ $oneText = '1'; $moreText = '%'; global $wpdb; $result = $wpdb->get_var(' SELECT COUNT(comment_ID) FROM '.$wpdb->comments.' WHERE comment_author_email = "'.get_comment_author_email().'"' ); if($result == 1): echo str_replace('%', $result, $oneText); elseif($result > 1): echo str_replace('%', $result, $moreText); endif; } |
To display an author’s total number of comments, use the function like this inside of your comments loop:
|
1 |
author_comment_count(); |
Source: http://www.wpmods.com/display-the-number-of-comments-by-author/
12. How to Display Most Popular Posts from a Specific Category
Put the code below, in your theme sidebar or wherever You want to display your popular posts from specific category
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php $args=array( 'cat' => 3, 'orderby' => 'comment_count', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 6, 'caller_get_posts'=> 1 ); $my_query = null; $my_query = new WP_Query($args); if( $my_query->have_posts() ) { ?> <ul> <?php while ($my_query->have_posts()) : $my_query->the_post(); ?> <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul> <?php } wp_reset_query(); ?> |
13. Automatically add Twitter and Facebook buttons to your posts
Paste the code below into your functions.php file, save it, and you’re done.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function share_this($content){ if(!is_feed() && !is_home()) { $content .= '<div class="share-this"> <a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a> <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> <div class="facebook-share-button"> <iframe src="http://www.facebook.com/plugins/like.php?href='. urlencode(get_permalink($post->ID)) .'&layout=button_count&show_faces=false&width=200&action=like&colorscheme=light&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:200px; height:21px;" allowTransparency="true"></iframe> </div> </div>'; } return $content; } add_action('the_content', 'share_this'); |
Source: http://www.wprecipes.com/automatically-add-twitter-and-facebook-buttons-to-your-posts
14. How to remove the “read more” jump
Paste the following snippet into your functions.php file:
|
1 2 3 4 |
function wdc_no_more_jumping($post) { return '<a href="'.get_permalink($post->ID).'" class="read-more">'.'Continue Reading'.'</a>'; } add_filter('excerpt_more', 'wdc_no_more_jumping'); |
Source: http://www.wprecipes.com/how-to-remove-the-read-more-jump
15. Output a google powered chart
Copy & paste this code into your functions.php
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
function chart_shortcode( $atts ) { extract(shortcode_atts(array( 'data' => '', 'colors' => '', 'size' => '400x200', 'bg' => 'ffffff', 'title' => '', 'labels' => '', 'advanced' => '', 'type' => 'pie' ), $atts)); switch ($type) { case 'line' : $charttype = 'lc'; break; case 'xyline' : $charttype = 'lxy'; break; case 'sparkline' : $charttype = 'ls'; break; case 'meter' : $charttype = 'gom'; break; case 'scatter' : $charttype = 's'; break; case 'venn' : $charttype = 'v'; break; case 'pie' : $charttype = 'p3'; break; case 'pie2d' : $charttype = 'p'; break; default : $charttype = $type; break; } if ($title) $string .= '&chtt='.$title.''; if ($labels) $string .= '&chl='.$labels.''; if ($colors) $string .= '&chco='.$colors.''; $string .= '&chs='.$size.''; $string .= '&chd=t:'.$data.''; $string .= '&chf='.$bg.''; return '<img title="'.$title.'" src="http://chart.apis.google.com/chart?cht='.$charttype.''.$string.$advanced.'" alt="'.$title.'" />'; } add_shortcode('chart', 'chart_shortcode'); |
Code: [chart data="41.52,37.79,20.67,0.03" bg="F7F9FA" labels="Reffering+sites|Search+Engines|Direct+traffic|Other" colors="058DC7,50B432,ED561B,EDEF00" size="488x200" title="Traffic Sources" type="pie"]
Source: http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress/
16. Automatic Social Media Links
This would go inside the loop, probably underneath the_content(), probably in your single.php file.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// bookmark on Delicious <a rel="nofollow" href="http://delicious.com/post?url=<?php the_permalink(); ?>&title=<?php echo urlencode(get_the_title($id)); ?>" title="Bookmark this post at Delicious">Bookmark at Delicious</a> // submit to Digg <a rel="nofollow" href="http://digg.com/submit?phase=2&url=<?php the_permalink(); ?>" title="Submit this post to Digg">Digg this!</a> // tweet on Twitter <a rel="nofollow" href="http://twitter.com/home?status=<?php echo urlencode("Currently reading: "); ?><?php the_permalink(); ?>" title="Share this article with your Twitter followers">Tweet this!</a> // submit to StumbleUpon <a rel="nofollow" href="http://www.stumbleupon.com/submit?url=<?php the_permalink(); ?>&title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post at StumbleUpon">Stumble this!</a> // share on Facebook <a rel="nofollow" href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Facebook">Share on Facebook</a> // submit to Blinklist <a rel="nofollow" href="http://blinklist.com/index.php?Action=Blink/addblink.php&url=<?php the_permalink(); ?>&Title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Blinklist" >Blink This!</a> // store on Furl <a rel="nofollow" href="http://furl.net/storeIt.jsp?t=<?php echo urlencode(get_the_title($id)); ?>&u=<?php the_permalink(); ?>" title="Share this post on Furl">Furl This!</a> // submit to Reddit <a rel="nofollow" href="http://reddit.com/submit?url=<?php the_permalink(); ?>&title=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Reddit">Share on Reddit</a> |
Source: http://css-tricks.com/snippets/wordpress/automatic-social-media-links/
17. Include jQuery in WordPress Theme
The following is the best way to go about it. Add the following to the theme’s functions.php file:
|
1 2 3 4 5 |
if( !is_admin()){ wp_deregister_script('jquery'); wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"), false, '1.3.2'); wp_enqueue_script('jquery'); } |
Source: http://css-tricks.com/snippets/wordpress/include-jquery-in-wordpress-theme/
18. Adding Classes To previous_posts_link() And next_posts_link() In WordPress
Simply insert the snippet bellow inside your theme’s function.php file.
|
1 2 3 4 5 6 |
add_filter('next_posts_link_attributes', 'posts_link_attributes'); add_filter('previous_posts_link_attributes', 'posts_link_attributes'); function posts_link_attributes(){ return 'class="styled-button"'; } |
What actually this snippet does is adding the html you return in the function to the anchor.
|
1 |
<a href=’link’ HERE></a> |
Source: http://wpcanyon.com/tipsandtricks/adding-attributes-to-previous-and-next-post-links/
19. Adding Classes to the Current Page Item in wp_nav_menu()
Copy & paste this code into your functions.php
|
1 2 3 4 5 6 7 8 9 10 |
add_filter( 'nav_menu_css_class', 'additional_active_item_classes', 10, 2 ); function additional_active_item_classes($classes = array(), $menu_item = false){ if(in_array('current-menu-item', $menu_item->classes)){ $classes[] = 'active'; } return $classes; } |
Source: http://wpcanyon.com/tipsandtricks/adding-classes-to-the-current-page-item-in-wp_nav_menu/
20. Show Top Commentators In WordPress Without A Plugin
put this snippet in your functions.php file inside your theme.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function top_comment_authors($amount = 5){ global $wpdb; $results = $wpdb->get_results(' SELECT COUNT(comment_author_email) AS comments_count, comment_author_email, comment_author, comment_author_url FROM '.$wpdb->comments.' WHERE comment_author_email != "" AND comment_type = "" AND comment_approved = 1 GROUP BY comment_author_email ORDER BY comments_count DESC, comment_author ASC LIMIT '.$amount ); $output = "<ul>"; foreach($results as $result){ $output .= "<li>".$result->comment_author."</li>"; } $output .= "</ul>"; echo $output; } |
Now you can call it anywhere in your theme using the top_comment_authors() function. By default it will show top 5 but if you want a different amount simply call it like top_comment_authors(7) which will show top 7 comment authors.
Source: http://wpcanyon.com/tipsandtricks/show-top-commentators-in-wordpress-without-a-plugin/
21. Display content to registered users only
Just paste the following code on your functions.php file:
|
1 2 3 4 5 6 7 8 9 10 11 |
add_shortcode( 'member', 'member_check_shortcode' ); function member_check_shortcode( $atts, $content = null ) { if ( is_user_logged_in() && !is_null( $content ) && !is_feed() ) return $content; return ''; } Once done, you can add the following to your posts to create a portion or text (or any other content) that will be only displayed to registered users: [member] This text will be only displayed to registered users. [/member] |
Source: http://snipplr.com/view.php?codeview&id=46936
22. Fixing WordPress 3.2′s HTML editor font
In your theme’s functions.php file or in a plugin file, add the following lines of code to change the font stack.
|
1 2 3 4 5 6 |
add_action( 'admin_head-post.php', 'devpress_fix_html_editor_font' ); add_action( 'admin_head-post-new.php', 'devpress_fix_html_editor_font' ); function devpress_fix_html_editor_font() { ?> <style type="text/css">#editorcontainer #content, #wp_mce_fullscreen { font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif; }</style> <?php } |
Source: http://devpress.com/blog/fixing-wordpress-3-2s-html-editor-font/
23. WordPress Add post thumbnails to RSS feed
Copy the function below into your functions.php:
|
1 2 3 4 5 6 7 8 9 10 |
function rss_post_thumbnail($content) { global $post; if(has_post_thumbnail($post->ID)) { $content = '<p>' . get_the_post_thumbnail($post->ID) . '</p>' . get_the_content(); } return $content; } add_filter('the_excerpt_rss', 'rss_post_thumbnail'); add_filter('the_content_feed', 'rss_post_thumbnail'); |
Source: http://snipplr.com/view.php?codeview&id=56180
24. Show a google map with a marker on it
Want to show a map and/or a marker on it? You’ll need a Google Maps API key for this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
function googlemap_shortcode( $atts ) { extract(shortcode_atts(array( 'width' => '500px', 'height' => '300px', 'apikey' => 'REPLACEME', 'marker' => '', 'center' => '', 'zoom' => '13' ), $atts)); if ($center) $setCenter = 'map.setCenter(new GLatLng('.$center.'), '.$zoom.');'; if ($marker) $setMarker = 'map.addOverlay(new GMarker(new GLatLng('.$marker.')));'; $rand = rand(1,100) * rand(1,100); return ' <script src="http://maps.google.com/maps?file=api&v=2.x&sensor=false&key='.$apikey.'" type="text/javascript"></script> <script type="text/javascript"> function initialize() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById("map_canvas_'.$rand.'")); '.$setCenter.' '.$setMarker.' map.setUIToDefault(); } } initialize(); </script> '; } add_shortcode('googlemap', 'googlemap_shortcode'); |
Source: http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress/
25. Display youtube video with embed shortcode
Paste the code below into your functions.php file, save it, and you’re done.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
function youtube($atts) { extract(shortcode_atts(array( "value" => 'http://', "width" => '475', "height" => '350', "name"=> 'movie', "allowFullScreen" => 'true', "allowScriptAccess"=>'always', ), $atts)); return '<object style="height: '.$height.'px; width: '.$width.'px"><param name="'.$name.'" value="'.$value.'"><param name="allowFullScreen" value="'.$allowFullScreen.'"></param><param name="allowScriptAccess" value="'.$allowScriptAccess.'"></param><embed src="'.$value.'" type="application/x-shockwave-flash" allowfullscreen="'.$allowFullScreen.'" allowScriptAccess="'.$allowScriptAccess.'" width="'.$width.'" height="'.$height.'"></embed></object>'; } add_shortcode("youtube", "youtube"); |
The code
|
1 |
[youtube value="http://www.youtube.com/watch?v=1aBSPn2P9bg"] |
Source: http://wpsnipp.com/index.php/functions-php/display-youtube-video-with-embed-shortcode/
26. Get custom field value with shortcode
Adding this PHP code to the functions.php of your wordpress theme will enable you to get custom field values using shortcode.
|
1 2 3 4 5 6 7 8 9 10 11 |
add_shortcode('field', 'shortcode_field'); function shortcode_field($atts){ extract(shortcode_atts(array( 'post_id' => NULL, ), $atts)); if(!isset($atts[0])) return; $field = esc_attr($atts[0]); global $post; $post_id = (NULL === $post_id) ? $post->ID : $post_id; return get_post_meta($post_id, $field, true); } |
|
1 2 |
[field "my_key"] [field "my_key" post_id=1] |
Source: http://wpsnipp.com/index.php/functions-php/get-custom-field-value-with-shortcode/
27. Obfuscate an email address
This simple shortcode will munge/create a link to an email address to help prevent spam. Not 100% foolproof but better than nothing (and a good basis to expand upon if you want to enhance it).
|
1 2 3 4 5 6 7 8 |
function munge_mail_shortcode( $atts , $content=null ) { for ($i = 0; $i < strlen($content); $i++) $encodedmail .= "&#" . ord($content[$i]) . ';'; return '<a href="mailto:'.$encodedmail.'">'.$encodedmail.'</a>'; } add_shortcode('mailto', 'munge_mail_shortcode'); |
Use: [mailto]email@yourdomain.com[/mailto].
Source: http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress/
28. Shortcode for HTML5 Video Tag in WordPress
Include this code in your functions.php file and you are ready to go:
|
1 2 3 4 5 6 7 8 9 |
function html5_video($atts, $content = null) { extract(shortcode_atts(array( "src" => '', "width" => '', "height" => '' ), $atts)); return '<video src="'.$src.'" width="'.$width.'" height="'.$height.'" controls autobuffer>'; } add_shortcode('video5', 'html5_video'); |
Now you can use the following shortcode in your post:
|
1 |
[video5 src="http://your-site/videos/your-video.mp4" width="720" height="480"] |
Source: http://bavotasan.com/2011/shortcode-for-html5-video-tag-in-wordpress/
29. WordPress shortcode snippet to display external files
Easiest way to accomplish this is through WordPress shortcode API with a simple code that you can add into the theme functions.php file:
|
1 2 3 4 5 6 7 8 9 10 |
function show_file_func( $atts ) { extract( shortcode_atts( array( 'file' => '' ), $atts ) ); if ($file!='') return @file_get_contents($file); } add_shortcode( 'show_file', 'show_file_func' ); |
This allows you to write something like this anywhere in your post:
|
1 |
[show_file file="http://www.prelovac.com/rise.html"] |
Source: http://www.prelovac.com/vladimir/wordpress-shortcode-snippet-to-display-external-files
30. Bloginfo Shortcode
The bloginfo() function in WordPress gives you access to lots of useful information about your site. See the complete list. To access all these values from inside Page/Post content itself, we can make a shortcode to return the values. Add this to your functions.php file in your theme:
|
1 2 3 4 5 6 7 |
function digwp_bloginfo_shortcode( $atts ) { extract(shortcode_atts(array( 'key' => '', ), $atts)); return get_bloginfo($key); } add_shortcode('bloginfo', 'digwp_bloginfo_shortcode'); |
Now you can output any of the values by calling that shortcode with “key”. For example, the name of your site:
|
1 |
[bloginfo key='name'] |
Or directly to images in your theme folder:
|
1 |
<img src="[bloginfo key='template_url']/images/logo.jpg" alt="[bloginfo key='name'] logo" /> |
Source: http://css-tricks.com/snippets/wordpress/bloginfo-shortcode/
You may also want to read the related article below.

One Response
Great list of snippets, thanks for including a few of mine in your list.
Cheers.