我有一个额外的网址,例如/products/myproduct/?v=iphone-x/transparent/*/Green
所以我需要的是为wordpress添加?v=iphone-x/透明/*/绿色到页面上的所有链接(只有‘<a href="">
’,没有'img src=""
‘或其他)
我已经设法做到了,但它有点“脏”。有没有什么巧妙的函数可以将参数添加到所有链接中?
我的代码如下:
function callback($buffer) {
// modify buffer here, and then return the updated code
$temp = explode('href="', $buffer);
$buffer = $temp[0];
array_shift($temp);
foreach($temp as $t){
$tt = explode('"', $t, 2);
$buffer .= 'href="'.$tt[0].'?v='.$_GET['v'].'"'.$tt[1];
}
return $buffer;
}
function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }
add_action('wp_head', 'buffer_start');
add_action('wp_footer', 'buffer_end');
发布于 2019-09-01 12:40:01
实现这一点的一种方法是挂接"the_content“过滤器。通过使用带有preg_replace_callback函数的正则表达式,您可以获得不错的结果。
function add_para( $content ) {
$content = preg_replace_callback(
"/href=(?>'|\")([^\"']+)(?>'|\")/",
function($m) {
print_r($m);
return "href='".$m[1]."/additional-param'";
},
$content);
return $content;
}
add_filter( 'the_content', 'add_para', 0 );
但是,您可能会遇到一些问题,特别是如果您的内容可能没有格式化(额外的空格,缺少标记..等)。
因此,对于我们来说,另一种选择是使用JS方法(例如jQuery),或者使用如下PHP DOM解析器:PHP Simple HTML DOM Parser
https://stackoverflow.com/questions/57740154
复制相似问题