[wp-hackers] Show only Shortcodes in Sidebar
Chris Jean
gaarai at gaarai.com
Mon Oct 26 12:43:28 UTC 2009
Looks like Andy beat me to the punch, but here's my solution just in
case it helps:
add_filter( 'the_content', 'just_shortcodes' );
function just_shortcodes( $content ) {
global $shortcode_tags;
$tagnames = array_keys( $shortcode_tags );
// $tagnames = array( 'video_shortcode' );
$tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) );
$regex = '\[('.$tagregexp.')\b(.*?)(?:(\/))?\](?:(.+?)\[\/\2\])?';
preg_match_all( '/' . $regex . '/s', $content, $matches,
PREG_PATTERN_ORDER );
return implode( '', $matches[0] );
}
I yanked most of this code from the get_shortcode_regex function in
wp-includes/shortcodes.php.
There are a few things of note here:
1. This is built as a filter, so all you have to do is use the
add_filter call before your sidebar code and then run
remove_filter( 'the_content', 'just_shortcodes' ) after the
sidebar code to return the_content calls to normal.
2. Since the $tagnames array is built inside the filter function, you
can tailor it to your needs to only include those shortcodes that
you wish to display. I show this with the commented out line that
manually sets the array. If you use this method, simply remove the
line above it as it is no longer needed.
3. The shortcodes are just slapped together with no spacing,
newlines, or breaks between them. You can change this by supplying
a different divider string in the first argument of the implode
function.
I hope this helps.
Chris Jean
http://gaarai.com/
http://wp-roadmap.com/
Andy Skelton wrote:
>>>> How to filter the_content so that only shortcodes display in that sidebar
>>>> and rest of content gets filtered out?
>>>>
>>> $content = strip_shortcodes($post->post_content);
>>>
>>>
>> This does the reverse. It removes the shortcodes. I want to display the
>> shortcodes only and anything except shortcodes should be filtered out.
>>
>
> Sorry, I flipped a bit. Look at the source for strip_shortcodes. It
> gets the regex pattern from get_shortcode_regex(). You can use that in
> preg_replace. Something like this extempore and untested snippet:
>
> $pattern = get_shortcode_regex();
> $pattern = str_replace('(.?)', '', $pattern);
> $pattern = str_replace('2', '3', $pattern);
> $content = $post->post_content;
> $shortcodes = preg_replace("/.*($pattern).*?/s", '$1', $content);
>
> Andy
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
>
More information about the wp-hackers
mailing list