假设我有一个页面,其中包含shortcodes
例如:
[myshortcode foo="bar" bar="bing"]
[anothershortcode foo="bing" bing="bar"]
那么我如何从我的自定义模板文件中读取这些内容,以便进行操作呢?假设我有一个页面,其中包含shortcodes
例如:
[myshortcode foo="bar" bar="bing"]
[anothershortcode foo="bing" bing="bar"]
那么我如何从我的自定义模板文件中读取这些内容,以便进行操作呢?do_shortcode
作用此函数依次调用get_shortcode_regex
, 它返回字符串中匹配短代码的正则表达式。使用此函数,我们可以自己获得所有短代码的列表:
$pattern = get_shortcode_regex();
preg_match_all( "/$pattern/s", $content, $matches );
print_r( $matches );
preg_match_all
放入所有匹配项$content
对于中的正则表达式$matches
. $matches
然后将包含一个二维数组。例如,对于这样的字符串:[first-shortcode no-content="true"]
This is shortcode testing content.
[sample-shortcode title="Testing"]This is a test[/sample-shortcode]
(假设短代码first-shortcode
和sample-shortcode
存在),print_r( $matches );
将输出:Array
(
[0] => Array
(
[0] => [first-shortcode no-content="true"]
[2] => [sample-shortcode title="Testing"]This is a test[/sample-shortcode]
)
[1] => Array
(
[0] =>
[1] =>
)
[2] => Array
(
[0] => first-shortcode
[1] => sample-shortcode
)
[3] => Array
(
[0] => no-content="true"
[1] => title="Testing"
)
[4] => Array
(
[0] =>
[1] =>
)
[5] => Array
(
[0] =>
[1] => This is a test
)
[6] => Array
(
[0] =>
[1] =>
)
)
如您所见,对于所有匹配项(短代码),第一级的七个数组中的每一个都有一个条目。$matches[0]
包含整个短代码,$matches[2]
包含短代码名称,$matches[3]
属性字符串和$matches[5]
短代码内容。我不确定你想操纵哪一部分,所以我不会详细介绍。你可以传递旗帜PREG_OFFSET_CAPTURE
到preg_match_all
在$flags
-参数这将确保字符串中发生匹配(短代码)的偏移量也被存储。
locate_template
, 它返回模板文件的路径,然后可以使用输出缓冲区获取其内容。ob_start();
locate_template( \'tpl-my-page-template.php\', true );
$contents = ob_get_contents();
ob_end_clean();
我不太确定你想要实现什么,但我的答案的第一部分至少是你需要的一部分:-)。我有一些预定义的链接,需要重定向到WP安装中的真实URL。不幸的是,我别无选择,只能使用提供给我的这些URL。格式为:http://mysite.com/redirect.html?p=pagenameWP安装在mysite的根目录下。com。我需要获取pagename查询变量,它不会与页面URL直接匹配,并将其重定向(301)到WP permalink。我尝试了几件事。htaccess具有重写功能,但运气不佳,这主要是因为还有WP permalinks重定向。有人以前做过这件事,或者知道最好的方法吗?更