Retrieve Wordpress Shortcodes
I'm looking to retrieve an object (or array) of the shortcodes on the page. So basically I have a shortcode where my user can insert anchors into a page, and I am looking to dynamically output a menu based on the shortcodes on the page. Is there any way to 开发者_Go百科retrieve the ones a user has put in at page render?
Here's what I did to be able to put parts of a post in a sidebar:
In header.php define a global varibale to hold the information:
// Initialize sidebar content.
$GLOBALS['mySidebar'] = '';
Each implementation of your shortcodes should add the information to that global variable. My shortcode just adds the HTML for the shortcode content, you should capture the meaning of the shortcode:
add_shortcode('sidebar', 'addToSidebar');
// Add content to the sidebar.
function addToSidebar($attributes, $content) {
$GLOBALS['mySidebar'] .= do_shortcode($content);
return '';
}
render the page elements, using the global variable:
<?php if (have_posts()) :
the_post();
// Get content first to retrieve the sidebar.
$content = get_the_content();
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content); ?>
<?php if (!empty($GLOBALS['mySidebar'])) :?>
<div id="sidebar"> <?php echo $GLOBALS['mySidebar']; ?> </div>
<?php endif; ?>
<div id="content">
... render the post.
<?php endif; ?>
精彩评论