WordPress:将自定义参数添加到所有URL

时间:2019-08-31 17:19:05

标签: wordpress

我在网址中添加了一个附加内容,例如/ products / myproduct /?v = iphone-x / transparent / * /绿色

所以我需要的是wordpress将?v = iphone-x / transparent / * / Green添加到页面上的所有链接(仅'<a href="">'s,没有'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');

1 个答案:

答案 0 :(得分:1)

可以实现此目的的一种方法是挂接到“ the_content”过滤器。通过将regexp与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

相关问题