php-提取内容中的简码参数-WordPress
作者:互联网
考虑如下的帖子内容:
[shortcode a="a_param"]
... Some content and shortcodes here
[shortcode b="b_param"]
.. Again some content here
[shortcode c="c_param"]
我有一个接受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),
)
我需要在the_content过滤器,wp_head过滤器或类似的工具中执行此操作.
我怎样才能做到这一点 ?
谢谢,
解决方法:
在wordpress get_shortcode_regex()中,函数返回用于在帖子内部搜索短代码的正则表达式.
$pattern = get_shortcode_regex();
然后将模式与发布内容进行preg_match
if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) )
如果返回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);
}
标签:wordpress-plugin,wordpress,php 来源: https://codeday.me/bug/20191027/1948110.html