Web Hosting
Web Hosting

Thursday, November 17, 2011

Using shortcodes everywhere in wordpress

At the moment, shortcodes in WordPress are processed only in post/page content. You can use them in lots of other places, though, if you enable them for each field you want. Here's how to use shortcodes in widgets, excerpts, comments, theme files, user descriptions, and category/tag/taxonomy descriptions.

Text Widgets

It's easy to make shortcodes work in text widgets. Just add the following to yourfunctions.php file:

add_filter( 'widget_text', 'shortcode_unautop');
add_filter( 'widget_text', 'do_shortcode');

The second line is the one that makes the shortcodes work, but you'll want to include both. 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.

Template Files

You can use shortcodes right in your theme! Use the do_shortcode() function, where the argument is a string that contains a shortcode.

For example, to print the output of the shortcode [foo] in a theme, add this to the file:

<?php do_shortcode('[foo]'); ?>

The do_shortcode() function accepts any text as its input. If the string contains a shortcode, that code will get processed. So, for example, you could manually process your post content for shortcodes like this:


<?php
$content = get_the_content();
echo do_shortcode($content);
?>

Comments

Do you trust your commenters enough to allow them to use shortcodes? This goes intofunctions.php:

add_filter( 'comment_text', 'shortcode_unautop');
add_filter( 'comment_text', 'do_shortcode' );

Excerpts

To enable shortcodes in excerpts, add these lines to your functions.php file:

add_filter( 'the_excerpt', 'shortcode_unautop');
add_filter( 'the_excerpt', 'do_shortcode');

User Descriptions

There is no filter (as far as I know) for the user description, so in order to display the description with shortcodes, you'll need to fetch the description string, then pass it to the do_shortcode() function. This would go into your theme file:

<?php
// $user_id = 3;
$userdata = get_userdata($user_id);
echo do_shortcode($userdata->description);
?>

Category, Tag, and Taxonomy Descriptions

These descriptions can be filtered, so the code for your functions.php file is simple:

add_filter( 'term_description', 'shortcode_unautop');
add_filter( 'term_description', 'do_shortcode' );

0 comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Facebook Themes