WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Extract shortcode out of the_content() (3 posts)

  1. Anydog
    Member
    Posted 1 year ago #

    Hi,
    I'm struggling with this:
    I would like to extract shortcode inserted in post with all atts and all into the do_shortcode() function.
    For example, I have shortcode entered in post:
    [icon icon_image="my_icon.png" size="large" style="dark"] , and I would really need it something like this:

    <?php
    $my_extracted_shortcode = function_with_shortcode_extraction();
    do_shortcode($my_extracted_shortcode);
    ?>

    So, problem is with obviously - function_with_shortcode_extraction() :). I tried something with get_shortcode_regex(), but it only returns all the shortcodes available ...

    Anyone ?

  2. Anydog
    Member
    Posted 1 year ago #

    Found a solution ! Here:
    http://bavotasan.com/2011/run-a-shortcode-anywhere-in-wordpress/

    So, i changed it a little bit, and added it into functions.php:

    <?php
    function extracted_shortcode()
    {
        global $post;
        $pattern = get_shortcode_regex();
    	preg_match('/'.$pattern.'/s', $post->post_content, $matches);
    	if (is_array($matches) && $matches[2] == 'icon') {
    	   $shortcode = $matches[0];
    	   echo do_shortcode($shortcode);
    	}
    }
    add_action( 'init', 'extracted_shortcode' );
    ?>

    and then later, in theme:
    <?php extracted_shortcode(); ?>

    Hope someone will have benefit of using this.

  3. Anydog
    Member
    Posted 1 year ago #

    Minor (but important) tweaks, because WP_DEBUG throw some nasty errors. Here's the (hopefully) error free code:

    <?php
    if ( ! function_exists( 'icon_shortcode' ) ) {
    function icon_shortcode()
    {
    	global $post;
    	if($post) {
    		$pattern = get_shortcode_regex();
    		preg_match('/'.$pattern.'/s', $post->post_content, $matches);
    		if( $matches ) :
    			if (is_array($matches) && $matches[2] == 'icon') {
    			   $shortcode = $matches[0];
    			   echo do_shortcode($shortcode);
    			}
    		endif; //$matches
    	} // endif $post
    }// end func. icon_shortcode
    }
    add_action( 'init', 'icon_shortcode' );
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic