You could use a few well placed actions to look ahead for your shortcode, if it's found set a flag and run additional actions to first strip the content of that shortcode, then a secondary one to execute that shortcode in the sidebar. Alongside all that create a simple action of your own inside the sidebar file and hook onto that when you need to print out the shortcode.
Not following? Don't blame you, i'm not always good at explaining ideas, so here's an example in code form..
First, inside your sidebar where you want the shortcode content appear, add something like..
<?php do_action( 'special_shortcode_content' ); ?>
We now have an action we can hook onto when a flag gets set.
Next we need to scan the posts, before the loop occurs, check for the existance of a particular shortcode, i'll use [sc]
as per your example and we can do that by hooking onto the_posts
. Rather than using a global, i prefer to just wrap the code into a class, and define a class variable inside the class to act as the flag.
class Page_Shortcode_to_Sidebar {
private $has_shortcode = false;
public function __construct() {
if( is_admin() )
return;
add_action( 'the_posts', array( $this, 'check_for_shortcode' ) );
add_filter( 'the_content', array( $this, 'remove_shortcode' ), 1 );
}
public function check_for_shortcode( $posts ) {
if( empty( $posts ) )
return $posts;
if( !is_page() )
return $posts;
foreach( $posts as $post ) {
if( !stripos( $post->post_content, '[sc]' ) )
continue;
$this->has_shortcode = true;
}
return $posts;
}
public function remove_shortcode( $content ) {
if( !$this->has_shortcode )
return $content;
$content = str_replace( '[sc]', '', $content );
add_action( 'special_shortcode_content', array( $this, 'do_shortcode' ) );
return $content;
}
public function do_shortcode() {
?>
<li><?php do_shortcode('[sc]'); ?></li>
<?php
}
}
$Page_Shortcode_to_Sidebar = new Page_Shortcode_to_Sidebar;
So basically what happens is this..
- The callback on
the_posts
checks each post for the shortcode, if found sets the flag.
- The callback on
the_content
executes later, and checks if the flag is set.
- If the flag is set, the shortcode is remove from the content and adds an action onto our custom sidebar action.
- It returns the content, minus the specific shortcode.
- The sidebar action occurs, and the shortcode content is produced.
If you're referring to your own shortcode that you created, and it's use in this way..
[sc]something[/sc]
..then you'll need something smarter to strip the shortcode contents from the post content.
If it's not used like that, then what i've provided above should do the job just fine.
Hope that helps.. :)