求助:从WordPress嵌套短码中提取ID值的函数修复
解决WordPress嵌套短码中提取download ID的问题
你的自定义函数失效的核心原因是get_shortcode_regex()只能匹配顶级短码——被[restrict]包裹的[download]会被识别为restrict短码的内容,而非独立短码,所以原函数无法捕捉到它。
下面提供两种可行的解决方法:
方案1:递归提取所有层级的目标短码
这个方法会遍历所有短码(包括嵌套在内层的),递归检查每一层短码的内容,确保不会漏掉任何目标短码:
function get_download_ids( $content, $target_shortcode = 'download' ) { $ids = array(); $pattern = get_shortcode_regex(); // 匹配所有短码(含外层短码) if ( preg_match_all( "/$pattern/s", $content, $matches, PREG_SET_ORDER ) ) { foreach ( $matches as $match ) { $shortcode_name = $match[2]; $shortcode_content = $match[5]; // 当前短码包裹的内容 // 若当前是目标短码,提取ID if ( $shortcode_name === $target_shortcode ) { $atts_str = trim( str_replace( $target_shortcode, '', $match[0] ), '[]' ); $atts = shortcode_parse_atts( $atts_str ); if ( ! empty( $atts['id'] ) ) { $ids[] = $atts['id']; } } // 递归检查当前短码内容里的嵌套短码 if ( ! empty( $shortcode_content ) ) { $nested_ids = get_download_ids( $shortcode_content, $target_shortcode ); $ids = array_merge( $ids, $nested_ids ); } } } return array_unique( $ids ); }
方案2:针对性正则直接提取ID(更简洁)
如果你的需求仅为提取download短码的ID,无需处理其他短码,可以直接用正则匹配所有符合格式的download短码,不管它是否被嵌套:
function get_download_ids( $content ) { $ids = array(); // 匹配[download id='xxx']或[download id="xxx"]格式的短码 preg_match_all( '/\[download\s+id=[\'"](\d+)[\'"]\s*\]/i', $content, $matches ); if ( ! empty( $matches[1] ) ) { $ids = array_unique( $matches[1] ); } return $ids; }
使用示例
调用函数时直接传入文章内容即可:
// 假设当前在文章循环内 $download_ids = get_download_ids( get_the_content() ); // 输出提取到的ID print_r( $download_ids );
内容的提问来源于stack exchange,提问作者Thanh Trần
相关产品推荐
相关产品推荐

