0

I do have an post/page where the shortcode "question" occurs many times. What is the best way to get an array of all the "question" shortcodes with their related parms?

[question a=1 b=2 c=3 ]
[question b=2 c=3 ]
[question a=1 b=2 ]
[question]

2 Answers 2

1
function wpse250308_get_questions() {
    global $post;
    if ( preg_match_all('/\[question(.*?)\]/', $post->post_content, $questions ) ) {
        $questions = array_key_exists( 1 , $questions) ? $questions[1] : array();
        // $questions will contain the array of the question shortcodes
        //Do your stuff
    }
}  

$post isn't available before wp. So, you have to hook on it or actions that fires later.

1
  • Thx alot. The questions are in array_key 0 $questions = array_key_exists( 0 , $questions) ? $questions[0] : array(); Commented Dec 25, 2016 at 10:52
0

You can also use the regular expression provided by WordPress itself using get_shortcode_regex:

function wpse250308_get_questions() {
    global $post;
    if ( preg_match_all(get_shortcode_regex('question'), $post->post_content, $questions ) ) {
        $questions = array_key_exists( 1 , $questions) ? $questions[1] : array();
        // $questions will contain the array of the question shortcodes
        // but also, get_shortcode_regex returns a regex that provides some useful capture groups:
        // the get_shortcode_regex from WP provides the matches:
        // 1 – An extra [ 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. 
        // 6 – An extra ] to allow for escaping shortcodes with double [[]]
        //Do your stuff
    }
}  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.