Using enclosing WordPress shortcodes to pass $content
I'm trying to use shortcodes for a glossary function. The function connects to a database, queries the word and returns the definition.
Currently, it works if I use self-closing shortcodes.
For example:
function defineGlossary($atts) {
extract(shortcode_atts(array(
'term' => '0'
), $atts));
// connect to database and grab definition
$glossary_output .= "<span title='";
$glossary_output .= $result_definition;
$glossary_output .= "'>";
$glossary_output .= $term;
$glossary_output .= "</span>";
return $glossary_output;
}
add_shortcode("glossary", "defineGlossary");
[glossary="administrator"] as a shortcode works great with this code. It returns
<span title="definition pulled from the database">administrator</span>.
I'd prefer to use an enclosing shortcose such as [glossary]administrator[/glossary] Unfortunately, I cannot get this to work since I don't know how (or if it's possible) to pass the $content as a variable (to send to the database and find the definition).
Update from below. If I simplify it to:
<?php
function defineGlossary($atts, $shortcodeContent = null) {
$glossary_output .= "<span title='";
$glossary_output .= "Sample Definition";
$glossary_output .= "'>";
$glossary_output .= $shortcodeContent;
$glossary_output .= "</span>";
return $glossary_output;
}
add_shortcode("glossary", "defi开发者_如何学CneGlossary");
?>
And use [glossary]administrator[/glossary] it just returns [glossary]administrator in the content.
Just add a second variable to your function to handle the shortcode content. This will be passed along if it exists.
function defineGlossary($atts, $shortcodeContent = null) {
if (is_null( $content )) {
//handle if shortcode isn't defined
}
// connect to database and grab definition
$glossary_output .= "<span title='";
$glossary_output .= $result_definition;
$glossary_output .= "'>";
$glossary_output .= $shortcodeContent;
$glossary_output .= "</span>";
return $glossary_output;
}
add_shortcode("glossary", "defineGlossary");
I didn't test this, but I think it does what you want.
精彩评论