alconebay Posted May 20, 2011 Share Posted May 20, 2011 I'm looking for a function that replaces user provided text blocks with code. I love the way wordpress handles shortcode and figured it would be easy to google and find a tutorial for doing the same thing outside of wordpress. But I'm not having much luck. Maybe I just don't know what terms to google. For those not familiar with Wordpress shortcode, here is a simple example: the user is creating their page using a wysiwyg editor. They want to insert a pedigree so they type [pedigree id=20] and when the page is displayed on the frontend, the "[pedigree id=20]" is replaced with the html to display the pedigree. I'll need to create about 20 different shortcodes with id (and possibly other/multiple) attributes. When googleing I found a few people wanting to do the same thing but the answers they got were just to use functions and to have the user type in some php. Knowing my users, that's not going to work. I need super easy, wordpress style, shortcode. I'm not looking for someone to type the code for me, just to point me in the right direction. Worse comes to worse, I'll try to extract the class/function from wordpress, but that might take me awhile since oop code still confuses me Quote Link to comment https://forums.phpfreaks.com/topic/236984-wordpress-style-shortcode-function/ Share on other sites More sharing options...
wildteen88 Posted May 20, 2011 Share Posted May 20, 2011 Sounds to me you need to create a dynamic BBCode Parser which replaces [pedigree id=20] with data from your database? If you look at how BBCode parsers are made you maybe able to come up with a solution. Quote Link to comment https://forums.phpfreaks.com/topic/236984-wordpress-style-shortcode-function/#findComment-1218121 Share on other sites More sharing options...
alconebay Posted May 20, 2011 Author Share Posted May 20, 2011 Ahhhh, yes. BBcode is what I needed to google. Thanks. It looks like it's just a matter of writing your own functions that use preg_replace or str_replace to get the job done. Quote Link to comment https://forums.phpfreaks.com/topic/236984-wordpress-style-shortcode-function/#findComment-1218162 Share on other sites More sharing options...
AbraCadaver Posted May 20, 2011 Share Posted May 20, 2011 Ahhhh, yes. BBcode is what I needed to google. Thanks. It looks like it's just a matter of writing your own functions that use preg_replace or str_replace to get the job done. Yes, but if your needs are as limited as you say, and will not likely grow more complex, then this should be fairly simple. In your example, what is pedigree (a column in a table)? What table? Quote Link to comment https://forums.phpfreaks.com/topic/236984-wordpress-style-shortcode-function/#findComment-1218170 Share on other sites More sharing options...
alconebay Posted May 20, 2011 Author Share Posted May 20, 2011 Yes, it's a pedigree from my mysql database. I have a page setup to query the database and display a pedigree based on the ID (pedigree.php). I'm hoping to have the shortcode parser see the block of code for a pedigree, grab the id, and then display the pedigree (maybe using an include 'pedigree.php'?) Quote Link to comment https://forums.phpfreaks.com/topic/236984-wordpress-style-shortcode-function/#findComment-1218177 Share on other sites More sharing options...
alconebay Posted May 20, 2011 Author Share Posted May 20, 2011 Cool. Check this out. I copy and pasted in the wordpress "shortcodes.php" (along with a couple of other functions from plugins.php that were referenced in shortcodes.php, I not sure yet what they do) and it work perfectly. Here is the code: 1. shortcodes.php (ripped from wordpress install) <?php /** * WordPress API for creating bbcode like tags or what WordPress calls * "shortcodes." The tag and attribute parsing or regular expression code is * based on the Textpattern tag parser. * * A few examples are below: * * [shortcode /] * [shortcode foo="bar" baz="bing" /] * [shortcode foo="bar"]content[/shortcode] * * Shortcode tags support attributes and enclosed content, but does not entirely * support inline shortcodes in other shortcodes. You will have to call the * shortcode parser in your function to account for that. * * {@internal * Please be aware that the above note was made during the beta of WordPress 2.6 * and in the future may not be accurate. Please update the note when it is no * longer the case.}} * * To apply shortcode tags to content: * * <code> * $out = do_shortcode($content); * </code> * * @link http://codex.wordpress.org/Shortcode_API * * @package WordPress * @subpackage Shortcodes * @since 2.5 */ /** * Container for storing shortcode tags and their hook to call for the shortcode * * @since 2.5 * @name $shortcode_tags * @var array * @global array $shortcode_tags */ $shortcode_tags = array(); /** * Add hook for shortcode tag. * * There can only be one hook for each shortcode. Which means that if another * plugin has a similar shortcode, it will override yours or yours will override * theirs depending on which order the plugins are included and/or ran. * * Simplest example of a shortcode tag using the API: * * <code> * // [footag foo="bar"] * function footag_func($atts) { * return "foo = {$atts[foo]}"; * } * add_shortcode('footag', 'footag_func'); * </code> * * Example with nice attribute defaults: * * <code> * // [bartag foo="bar"] * function bartag_func($atts) { * extract(shortcode_atts(array( * 'foo' => 'no foo', * 'baz' => 'default baz', * ), $atts)); * * return "foo = {$foo}"; * } * add_shortcode('bartag', 'bartag_func'); * </code> * * Example with enclosed content: * * <code> * // [baztag]content[/baztag] * function baztag_func($atts, $content='') { * return "content = $content"; * } * add_shortcode('baztag', 'baztag_func'); * </code> * * @since 2.5 * @uses $shortcode_tags * * @param string $tag Shortcode tag to be searched in post content. * @param callable $func Hook to run when shortcode is found. */ function add_shortcode($tag, $func) { global $shortcode_tags; if ( is_callable($func) ) $shortcode_tags[$tag] = $func; } /** * Removes hook for shortcode. * * @since 2.5 * @uses $shortcode_tags * * @param string $tag shortcode tag to remove hook for. */ function remove_shortcode($tag) { global $shortcode_tags; unset($shortcode_tags[$tag]); } /** * Clear all shortcodes. * * This function is simple, it clears all of the shortcode tags by replacing the * shortcodes global by a empty array. This is actually a very efficient method * for removing all shortcodes. * * @since 2.5 * @uses $shortcode_tags */ function remove_all_shortcodes() { global $shortcode_tags; $shortcode_tags = array(); } /** * Search content for shortcodes and filter shortcodes through their hooks. * * If there are no shortcode tags defined, then the content will be returned * without any filtering. This might cause issues when plugins are disabled but * the shortcode will still show up in the post or content. * * @since 2.5 * @uses $shortcode_tags * @uses get_shortcode_regex() Gets the search pattern for searching shortcodes. * * @param string $content Content to search for shortcodes * @return string Content with shortcodes filtered out. */ function do_shortcode($content) { global $shortcode_tags; if (empty($shortcode_tags) || !is_array($shortcode_tags)) return $content; $pattern = get_shortcode_regex(); return preg_replace_callback('/'.$pattern.'/s', 'do_shortcode_tag', $content); } /** * Retrieve the shortcode regular expression for searching. * * The regular expression combines the shortcode tags in the regular expression * in a regex class. * * The regular expresion contains 6 different sub matches to help with parsing. * * 1/6 - An extra [ or ] to allow for escaping shortcodes with double [[]] * 2 - The shortcode name * 3 - The shortcode argument list * 4 - The self closing / * 5 - The content of a shortcode when it wraps some content. * * @since 2.5 * @uses $shortcode_tags * * @return string The shortcode search regular expression */ function get_shortcode_regex() { global $shortcode_tags; $tagnames = array_keys($shortcode_tags); $tagregexp = join( '|', array_map('preg_quote', $tagnames) ); // WARNING! Do not change this regex without changing do_shortcode_tag() and strip_shortcodes() return '(.?)\[('.$tagregexp.')\b(.*?)(?\/))?\](?.+?)\[\/\2\])?(.?)'; } /** * Regular Expression callable for do_shortcode() for calling shortcode hook. * @see get_shortcode_regex for details of the match array contents. * * @since 2.5 * @access private * @uses $shortcode_tags * * @param array $m Regular expression match array * @return mixed False on failure. */ function do_shortcode_tag( $m ) { global $shortcode_tags; // allow [[foo]] syntax for escaping a tag if ( $m[1] == '[' && $m[6] == ']' ) { return substr($m[0], 1, -1); } $tag = $m[2]; $attr = shortcode_parse_atts( $m[3] ); if ( isset( $m[5] ) ) { // enclosing tag - extra parameter return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, $m[5], $tag ) . $m[6]; } else { // self-closing tag return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, NULL, $tag ) . $m[6]; } } /** * Retrieve all attributes from the shortcodes tag. * * The attributes list has the attribute name as the key and the value of the * attribute as the value in the key/value pair. This allows for easier * retrieval of the attributes, since all attributes have to be known. * * @since 2.5 * * @param string $text * @return array List of attributes and their value. */ function shortcode_parse_atts($text) { $atts = array(); $pattern = '/(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/'; $text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text); if ( preg_match_all($pattern, $text, $match, PREG_SET_ORDER) ) { foreach ($match as $m) { if (!empty($m[1])) $atts[strtolower($m[1])] = stripcslashes($m[2]); elseif (!empty($m[3])) $atts[strtolower($m[3])] = stripcslashes($m[4]); elseif (!empty($m[5])) $atts[strtolower($m[5])] = stripcslashes($m[6]); elseif (isset($m[7]) and strlen($m[7])) $atts[] = stripcslashes($m[7]); elseif (isset($m[8])) $atts[] = stripcslashes($m[8]); } } else { $atts = ltrim($text); } return $atts; } /** * Combine user attributes with known attributes and fill in defaults when needed. * * The pairs should be considered to be all of the attributes which are * supported by the caller and given as a list. The returned attributes will * only contain the attributes in the $pairs list. * * If the $atts list has unsupported attributes, then they will be ignored and * removed from the final returned list. * * @since 2.5 * * @param array $pairs Entire list of supported attributes and their defaults. * @param array $atts User defined attributes in shortcode tag. * @return array Combined and filtered attribute list. */ function shortcode_atts($pairs, $atts) { $atts = (array)$atts; $out = array(); foreach($pairs as $name => $default) { if ( array_key_exists($name, $atts) ) $out[$name] = $atts[$name]; else $out[$name] = $default; } return $out; } /** * Remove all shortcode tags from the given content. * * @since 2.5 * @uses $shortcode_tags * * @param string $content Content to remove shortcode tags. * @return string Content without shortcode tags. */ function strip_shortcodes( $content ) { global $shortcode_tags; if (empty($shortcode_tags) || !is_array($shortcode_tags)) return $content; $pattern = get_shortcode_regex(); return preg_replace('/'.$pattern.'/s', '$1$6', $content); } function _wp_filter_build_unique_id($tag, $function, $priority) { global $wp_filter; static $filter_id_count = 0; if ( is_string($function) ) return $function; if ( is_object($function) ) { // Closures are currently implemented as objects $function = array( $function, '' ); } else { $function = (array) $function; } if (is_object($function[0]) ) { // Object Class Calling if ( function_exists('spl_object_hash') ) { return spl_object_hash($function[0]) . $function[1]; } else { $obj_idx = get_class($function[0]).$function[1]; if ( !isset($function[0]->wp_filter_id) ) { if ( false === $priority ) return false; $obj_idx .= isset($wp_filter[$tag][$priority]) ? count((array)$wp_filter[$tag][$priority]) : $filter_id_count; $function[0]->wp_filter_id = $filter_id_count; ++$filter_id_count; } else { $obj_idx .= $function[0]->wp_filter_id; } return $obj_idx; } } else if ( is_string($function[0]) ) { // Static Calling return $function[0].$function[1]; } } function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) { global $wp_filter, $merged_filters; $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority); $wp_filter[$tag][$priority][$idx] = array('function' => $function_to_add, 'accepted_args' => $accepted_args); unset( $merged_filters[ $tag ] ); return true; } add_filter('the_content', 'do_shortcode', 11); // AFTER wpautop() //end of shortcodes.php 2. my_custom_shortcodes.php <?php //pedigree shortcode test function pedigree($atts) { extract( shortcode_atts( array( 'pedid' => 'error, no id was entered', ), $atts ) ); $pedigree = include 'pedigree_preview.php'; echo $pedigree; } add_shortcode('ped', 'pedigree'); ?> 3. pedigree_preview.php <?php $query="SELECT * FROM pedigree WHERE id='$pedid'"; $result=mysql_query($query); //blah blah blah ?> <div id="pedigree-content"> Huge pedigree chart goes here </div> 4. frontend_view.php (this is where the user's wysiwyg content is displayed) <?php include 'dbconnect.php'; include 'shortcodes.php'; include 'my_custom_shortcodes.php'; //I run the sql to get the user's wysiwyg content from the database and put it in the variable $content //for sake of example, I manually provide some content $content= 'Hi, check out this pedigree I made: [ped pedid="1"]'; do_shortcode($content); ?> I tested it and it works perfectly. I'll might go through the shortcodes.php and see if I can edit it down some. I'm not sure what all it's doing yet, but it works. Quote Link to comment https://forums.phpfreaks.com/topic/236984-wordpress-style-shortcode-function/#findComment-1218213 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.