获取字符串中的短码数组

时间:2016-12-24 作者:user3361559

我确实有一个帖子/页面,其中短代码“问题”出现了很多次。获取所有“问题”快捷码及其相关参数数组的最佳方法是什么?

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

2 个回复
最合适的回答,由SO网友:Abhik 整理而成

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 以前不可用wp. 所以,你必须抓住它或稍后激发的动作。

SO网友:BernhardWebstudio

您还可以使用WordPress本身提供的正则表达式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
    }
}  

相关推荐

Show form per shortcode

这是我的密码。我想按短代码显示它。$user_id = get_current_user_id(); $balance = mycred_get_users_balance( $user_id ); echo "Current Balance: ".$balance."<br><br>"; if ($_POST && $_SERVER["REQUEST_METHOD"] == &qu