13 Useful WordPress Shortcodes


1. WordPress Related Posts Shortcode

[php]
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’);
[/php]

source : http://snipplr.com/view/43845/wordpress-related-posts-shortcode/

2.WordPress Related Posts w/ Thumbs

Posts with thumbs by category

[php]

<?php $orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;

$args=array(
‘category__in’ => $category_ids,
‘post__not_in’ => array($post->ID),
‘posts_per_page’=> 3, // Number of related posts that will be shown.
‘caller_get_posts’=>1
);

$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo ‘<h3>Related Posts</h3><ul>’;
while( $my_query->have_posts() ) {
$my_query->the_post();?>
<li><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></li>
<?
}
echo ‘</ul>’;
}
}
$post = $orig_post;
wp_reset_query(); ?>

[/php]

source : http://snipplr.com/view/46026/

3. WordPress Image Gallery Short Code Using Post Attachments

courtesy Pippin Williamson (http://pippinsplugins.com/image-gallery-short-code-using-post-attachments/)

use shortcode [photo_gallery] to display the gallery

[php]
function pippin_gallery_shortcode( $atts, $content = null ) {

extract( shortcode_atts( array(
‘size’ => ”
), $atts ) );

$image_size = ‘medium’;
if($size =! ”) { $image_size = $size; }

$images = get_children(array(
‘post_parent’ => get_the_ID(),
‘post_type’ => ‘attachment’,
‘numberposts’ => -1,
‘orderly’ => ‘menu_order’,
//’exclude’ => get_post_thumbnail_id(), — uncomment to exclude post thumbnail
‘post_mime_type’ => ‘image’,
)
);

if($images) {
$gallery = ‘<ul class="gallery clearfix">’;
foreach( $images as $image ) {
$gallery .= ‘<li>’;
$gallery .= ‘<a href="’ . wp_get_attachment_url($image->ID) . ‘" rel="shadowbox">’;
$gallery .= wp_get_attachment_image($image->ID, $image_size);
$gallery .= ‘</a>’;
$gallery .= ‘</li>’;
}
$gallery .= ‘</ul>’;

return $gallery;
}

}
add_shortcode(‘photo_gallery’, ‘pippin_gallery_shortcode’);
[/php]

source : http://snipplr.com/view/61936/wordpress-image-gallery-short-code-using-post-attachments

4. [Wordpress shortcode] Show content for logged in users

Usage:

[hide]Hide content for guest[/hide] *Doesn’t work on comments! add this into your function.php template file

[php]

<?php
add_shortcode("hide","hide_shortcode");

function hide_shortcode($x,$text=null){
if(!is_user_logged_in()){
return "You have to been registered and logged in to see this content";
}else{
return do_shortcode($text);
}
}
?>

[/php]

source: http://snipplr.com/view/60658/wordpress-shortcode-show-content-for-logged-in-users

5. WordPress shortcode: Automatically insert image by file name

[php]

//The first thing to do is to paste this code on your functions.php file:

function image_shortcode($atts, $content = null) {
extract( shortcode_atts( array(
‘name’ => ”,
‘align’ => ‘right’,
‘ext’ => ‘png’,
‘path’ => ‘/wp-content/uploads/’,
‘url’ => ”
), $atts ) );
$file=ABSPATH."$path$name.$ext";
if (file_exists($file)) {
$size=getimagesize($file);
if ($size!==false) $size=$size[3];
$output = "<img src=’".get_option(‘siteurl’)."$path$name.$ext’ alt=’$name’ $size align=’$align’ class=’align$align’ />";
if ($url) $output = "<a href=’$url’ title=’$name’>".$output.’</a>’;
return $output;
}
else {
trigger_error("’$path$name.$ext’ image not found", E_USER_WARNING);
return ”;
}
}
add_shortcode(‘image’,’image_shortcode’);

/*
Once done, you can use the image shortcode in your posts. For example, the following line of code: [image name=cat]
*/

[/php]

6. Allow shortcodes in WordPress widgets

If you want to be able to use shortcodes in WordPress widgets, place the snippet below into your functions.php, or custom_functions.php file.

[php]
add_filter(‘widget_text’, ‘do_shortcode’)
[/php]

source : http://snipplr.com/view/54618/allow-shortcodes-in-wordpress-widgets

7. Make shortcode for dynamics links for widgets in wordpress

[php]

<?php
/* Short code [a href="pageId" class"clasName"]link[/a] */

/*If you check “add paragraphs automatically” on the widget, WordPress will apply the autop filter — the one that turns your line breaks into paragraph and break tags. If a shortcode is on its own line, it would normally get wrapped in a paragraph tag. The first line prevents that from happening.

thanks to http://sillybean.net/2010/02/using-shortcodes-everywhere/
*/

add_filter( ‘widget_text’, ‘shortcode_unautop’);

//Add shortcode functionality to widgets
add_filter(‘widget_text’, ‘do_shortcode’);

function a_func($atts, $content) {
extract(shortcode_atts(array(
‘href’ => ‘ ‘,
‘class’ => ‘ ‘,
), $atts));

$theLink = ‘<a class="’. $class .’" href="’. get_permalink($href) .’">’. $content .’</a>’;

return "{$theLink}";
}

add_shortcode(‘a’, ‘a_func’);
?>

[/php]

source : http://snipplr.com/view/54344/make-shortcode-for-dynamics-links-for-widgets-in-wordpress

8. WordPress RSS shortcode

shortcode : [rss size="10" feed="http://wordpress.org/news/feed/" date="true"]

[php]

*
* Re-usable RSS feed reader with shortcode
*/
if ( !function_exists(‘base_rss_feed’) ) {
function base_rss_feed($size = 5, $feed = ‘http://wordpress.org/news/feed/’, $date = false, $cache_time = 1800)
{
// Include SimplePie RSS parsing engine
include_once ABSPATH . WPINC . ‘/feed.php’;

// Set the cache time for SimplePie
add_filter( ‘wp_feed_cache_transient_lifetime’, create_function( ‘$a’, "return cache_time;" ) );

// Build the SimplePie object
$rss = fetch_feed($feed);

// Check for errors in the RSS XML
if (!is_wp_error( $rss ) ) {

// Set a limit for the number of items to parse
$maxitems = $rss->get_item_quantity($size);
$rss_items = $rss->get_items(0, $maxitems);

// Store the total number of items found in the feed
$i = 0;
$total_entries = count($rss_items);

// Output HTML
$html = "<ul class=’feedlist’>";
foreach ($rss_items as $item) {
$i++;

// Add a class of "last" to the last item in the list
if( $total_entries == $i ) {
$last = " class=’last’";
} else {
$last = "";
}

// Store the data we need from the feed
$title = $item->get_title();
$link = $item->get_permalink();
$desc = $item->get_description();
$date_posted = $item->get_date(‘d/m/Y’);
//$desc = strip_tags($desc);
$desc =wp_kses(trim($desc),array());
$desc = apply_filters(‘the_excerpt’, $desc);

$desc = strip_tags($desc,"");
//print(‘ — strlen : ‘.strlen($desc));
$excerpt_length = 100;
$words = explode(‘ ‘, $desc, $excerpt_length + 1);
//print(‘ — words : ‘.count($words));
if(count($words) > $excerpt_length) :
array_pop($words);
array_push($words, ‘…’);
$desc = implode(‘ ‘, $words);
endif;
$desc = trim($desc);

while(strpos($desc, ‘ ‘) !== false)
$desc = str_replace(‘ ‘, ‘ ‘, $desc); //eventually $s will == ‘/’
$desc = substr(($desc),10);
// Output
$html .= "<li id=’post-$i’$last>";
$html .= "<h4><a href=’$link’>$title</a></h4>";
if( $date == true ) $html .= "<span class=’date’>$date_posted</span>";
$html .= "<div class=’rss-entry’>$desc</a></h4></div>";
$html .= "</li>";
}
$html .= "</ul>";

} else {

$html = "An error occurred while parsing your RSS feed. Check that it’s a valid XML file.";

}

return $html;
}
}
/** Define [rss] shortcode */
if( function_exists(‘base_rss_feed’) && !function_exists(‘base_rss_shortcode’) ) {
function base_rss_shortcode($atts) {
extract(shortcode_atts(array(
‘size’ => ’10′,
‘feed’ => ‘http://wordpress.org/news/feed/’,
‘date’ => false,
), $atts));

$content = base_rss_feed($size, $feed, $date);
return $content;
}
add_shortcode("rss", "base_rss_shortcode");
}

[/php]

source : http://snipplr.com/view/50654/wordpress-rss–shortcode

9. WordPress shortcode: Display content to registered users only

WordPress shortcode: Display content to registered users only

[php]
Just paste the following code on your functions.php file:
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]
[/php]

source : http://snipplr.com/view/46936/wordpress-shortcode-display-content-to-registered-users-only

10. Integrate Adsense ads

Adsense is probably the easiest way to make money online and most bloggers are using it in order to earn an online income. using widgets , you can easily add Adsense ads in your blog sidebar, but the best way to get clicks from visitors is definitely to integrate Adsense in your posts. The whole process is incredibly easy, using WordPress shortcodes.

[php]
function showads() {
return ‘<script type="text/javascript"><!–
google_ad_client = "pub-3637220125174754";
google_ad_slot = "4668915978";
google_ad_width = 468;
google_ad_height = 60;
//–>
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
‘;
}

add_shortcode(‘adsense’, ‘showads’);
[/php]

source : http://www.wprecipes.com/how-to-embed-adsense-anywhere-on-your-posts

11. Automatically create a short url for Twitter

[php]

function subzane_shorturl($atts) {
extract(shortcode_atts(array(
‘url’ => ”,
‘name’ => ”,
), $atts));
$request = ‘http://u.nu/unu-api-simple?url=’ . urlencode($url);
$short_url = file_get_contents($request);
if (substr($short_url, 0, 4) == ‘http’) {
$name = empty($name)?$short_url:$name;
return ‘<a href="’.$short_url.’">’.$name.’</a>’;
} else {
$name = empty($name)?$url:$name;
return ‘<a href="’.$url.’">’.$name.’</a>’;
}
}
add_shortcode(‘shorturl’, ‘subzane_shorturl’);

[/php]

source : http://www.subzane.com/2009/05/shortcode-advantage-unus-url-shortener

12. Display the last image attached to post

Instead of dealing with image url, a simple shortcode can retrieve and display the last image attached to post:

[php]
function sc_postimage($atts, $content = null) {
extract(shortcode_atts(array(
"size" => ‘thumbnail’,
"float" => ‘none’
), $atts));
$images =& get_children( ‘post_type=attachment&post_mime_type=image&post_parent=’ . get_the_id() );
foreach( $images as $imageID => $imagePost )
$fullimage = wp_get_attachment_image($imageID, $size, false);
$imagedata = wp_get_attachment_image_src($imageID, $size, false);
$width = ($imagedata[1]+2);
$height = ($imagedata[2]+2);
return ‘<div class="postimage" style="width: ‘.$width.’px; height: ‘.$height.’px; float: ‘.$float.’;">’.$fullimage.’</div>’;
}
add_shortcode("postimage", "sc_postimage");
[/php]

source : http://www.wprecipes.com/wordpress-shortcode-easily-display-the-last-image-attached-to-post

13. Remove WordPress automatic formatting

If you’re used to display code snippets on your blog, you know that WordPress automatic formatting can be a pain for developers. The solution is simple: Using a shortcode to remove the auto-formatting functions on certain portions of text.

[php]
function my_formatter($content) {
$new_content = ”;
$pattern_full = ‘{(\[raw\].*?\[/raw\])}is’;
$pattern_contents = ‘{\[raw\](.*?)\[/raw\]}is’;
$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

foreach ($pieces as $piece) {
if (preg_match($pattern_contents, $piece, $matches)) {
$new_content .= $matches[1];
} else {
$new_content .= wptexturize(wpautop($piece));
}
}

return $new_content;
}

remove_filter(‘the_content’, ‘wpautop’);
remove_filter(‘the_content’, ‘wptexturize’);

add_filter(‘the_content’, ‘my_formatter’, 99);
[/php]

source : http://wordpress.org/support/topic/280732




Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>