提取内容中的简码参数-Wordpress

MeC*_*eCe 5 php wordpress wordpress-plugin

考虑如下的帖子内容:

[shortcode a="a_param"]
... Some content and shortcodes here
[shortcode b="b_param"]
.. Again some content here
[shortcode c="c_param"]
Run Code Online (Sandbox Code Playgroud)

我有一个接受3个或更多参数的简码。我想找出在内容及其数组中的参数中使用简码的次数,例如

array (
[0] => array(a => a_param, b=> null, c=>null),
[1] => array(a => null, b=> b_param, c=>null),
[2] => array(a => null, b=> null, c=>c_param),
)
Run Code Online (Sandbox Code Playgroud)

我需要在the_content过滤器,wp_head过滤器或类似的工具中执行此操作。

我怎样才能做到这一点 ?

谢谢,

Tam*_*n C 8

在wordpress中,get_shortcode_regex()函数返回正则表达式,用于搜索帖子中的短代码。

$pattern = get_shortcode_regex();
Run Code Online (Sandbox Code Playgroud)

然后将模式与发布内容进行preg_match

if (   preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) )
Run Code Online (Sandbox Code Playgroud)

如果返回true,则提取的短代码详细信息将保存在$ matches变量中。

尝试

global $post;
$result = array();
//get shortcode regex pattern wordpress function
$pattern = get_shortcode_regex();


if (   preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) )
{
    $keys = array();
    $result = array();
    foreach( $matches[0] as $key => $value) {
        // $matches[3] return the shortcode attribute as string
        // replace space with '&' for parse_str() function
        $get = str_replace(" ", "&" , $matches[3][$key] );
        parse_str($get, $output);

        //get all shortcode attribute keys
        $keys = array_unique( array_merge(  $keys, array_keys($output)) );
        $result[] = $output;

    }
    //var_dump($result);
    if( $keys && $result ) {
        // Loop the result array and add the missing shortcode attribute key
        foreach ($result as $key => $value) {
            // Loop the shortcode attribute key
            foreach ($keys as $attr_key) {
                $result[$key][$attr_key] = isset( $result[$key][$attr_key] ) ? $result[$key][$attr_key] : NULL;
            }
            //sort the array key
            ksort( $result[$key]);              
        }
    }

    //display the result
    print_r($result);


}
Run Code Online (Sandbox Code Playgroud)

  • 如果属性值中有任何空格,这将不起作用,因为 str_replace() 也会影响它们。 (2认同)