Wordpress remove shortcode and save for use elsewhere
Function to grab First Gallery shortcode from post content:
// Return first gallery shortcodefunction get_shortcode_gallery ( $post = 0 ) { if ( $post = get_post($post) ) { $post_gallery = get_post_gallery($post, false); if ( ! empty($post_gallery) ) { $shortcode = "[gallery"; foreach ( $post_gallery as $att => $val ) { if ( $att !== 'src') { if ( $att === 'size') $val = "full"; // Set custom attribute value $shortcode .= " ". $att .'="'. $val .'"'; // Add attribute name and value ( attribute="value") } } $shortcode .= "]"; return $shortcode; } }}// Example of how to use: echo do_shortcode( get_shortcode_gallery() );
Function to delete First gallery shortcode from Post content:
// Deletes first gallery shortcode and returns contentfunction strip_shortcode_gallery( $content ) { preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER ); if ( ! empty( $matches ) ) { foreach ( $matches as $shortcode ) { if ( 'gallery' === $shortcode[2] ) { $pos = strpos( $content, $shortcode[0] ); if ($pos !== false) return substr_replace( $content, '', $pos, strlen($shortcode[0]) ); } } } return $content;}// Example of how to use:$content = strip_shortcode_gallery( get_the_content() ); // Delete first gallery shortcode from post content$content = str_replace( ']]>', ']]>', apply_filters( 'the_content', $content ) ); // Apply filter to achieve the same output that the_content() returnsecho $content;
just use the get_shortcode_regex():
<?php$pattern = get_shortcode_regex();preg_match_all('/'.$pattern.'/s', $post->post_content, $shortcodes);?>
that will return an array of all the shortcodes in your content, which you can then output wherever you feel, like so:
<?phpecho do_shortcode($shortcodes[0][1]);?>
similarly, you could use the array entries to check for shortcodes in your content and remove them with str_replace():
<?php$content = $post->post_content;$content = str_replace($shortcodes[0][1],'',$content);?>