Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return only the shortcode from post?

Tags:

php

wordpress

Is it possible to filter out only the shortcode from the post and then run the shortcode?

My page looks like this:

[summary img="images/latest.jpg"]

This here is the summary

[/summary]

Lots of text here...

And i just want to display the shortcode on a specific page.

Tried using regular expressions, but they dont seem to work:

$the_query = new WP_Query('category_name=projects&showposts=1');

    //loop
    while ( $the_query->have_posts() ) : $the_query->the_post();
        echo '<b>';
        the_title();
        echo '</b>';
        echo '<p>';

        $string = get_the_content();

        if (preg_match("[\\[[a-zA-Z]+\\][a-zA-Z ]*\\[\/[a-zA-Z]+\\]]", $string , $matches)) {
            echo "Match was found <br />";
            echo $matches[0];
        }

        echo '</p>';
    endwhile;

Any idéas?

EDIT:

Found a temporary solution.

while ( $the_query->have_posts() ) : $the_query->the_post();

    $content = str_replace(strip_shortcodes(get_the_content()),"",get_the_content());               
    echo do_shortcode($content);

endwhile;

I saw that wordpress had a function for striping shortcodes but not for strip content. So i replaced the stripped content string from the whole post to get just the shortcode. The only bad thing about this that the shortcodes have to be in the beginning of the posts.

like image 266
Richard Avatar asked Dec 06 '22 21:12

Richard


1 Answers

Better answer is:

$pattern = get_shortcode_regex();
preg_match('/'.$pattern.'/s', $post->post_content, $matches);
if (is_array($matches) && $matches[2] == 'the_shortcode_name') {
   $shortcode = $matches[0];
   echo do_shortcode($shortcode);
}

It will search through the post content for a shortcode called “the_shortcode_name”. If it finds it, it will store the shortcode in the $matches variable. Easy to run it from there.

like image 56
two7s_clash Avatar answered Dec 10 '22 11:12

two7s_clash