如何生成动态外部链接


How to generate dynamic external link?

我是php和css的新手。
我的目标是把两个图标放入wordpress网站的主menù。这些图标应该指向我的域名的动态外部链接。
我的主题的header.php代码是:

<div id="flags" style="position:absolute;left:97%;top:10px; width:300px; height:30px; background-color:transparent">
    <a href="mydomain.com/aaa/"><img src="wp-content/themes/minimable-premium/templates/it-icon-24.png" /></a>
    <a href="mydomain.com/bbb/"><img src="wp-content/themes/minimable-premium/templates/uk-icon-24.png" /></a>
</div>

我需要取当前的URL,用我选择的字符串替换其中的一部分。例如,在第一个url中,输入字符串"aaa"与"ccc"。因此,图标链接到新地址。

我试着这样做:

<div id="flags" style="position:absolute;left:97%;top:10px; width:300px; height:30px; background-color:transparent">
    <?php
        $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $strEng = "eng";
        $strIta = "ita";
        $new_link = str_replace($strEng,$strIta, $actual_link);
    ?>
    <div id="banner" onclick="window.location.href='$new_link'" style="cursor: pointer">
        <img src="wp-content/themes/minimable-premium/templates/it-icon-24.png" />
    </div>
    <a href="mydomain.com/bbb/"><img src="wp-content/themes/minimable-premium/templates/uk-icon-24.png" /></a>
</div>

你能告诉我如何写正确的代码和在哪些文件中吗?

不能像在普通变量中那样直接在字符串中引用数组元素。您必须将多个字符串与.运算符组合起来。查看我在第3行所做的更改:

<div id="flags" style="position:absolute;left:97%;top:10px; width:300px; height:30px; background-color:transparent">
            <?php
                $actual_link = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
                $strEng = "eng";
                $strIta = "ita";
                $new_link = str_replace($strEng,$strIta, $actual_link);
            ?>
            <div id="banner" onclick="window.location.href='$new_link'" style="cursor: pointer">
                <img src="wp-content/themes/minimable-premium/templates/it-icon-24.png" />
            </div>
            <a href="mydomain.com/bbb/"><img src="wp-content/themes/minimable-premium/templates/uk-icon-24.png" /></a>
</div>

看起来你想做一个可翻译的网站。我认为你应该做的是使用WordPress的大型插件社区来让你的网站可翻译。(WPML, WordPress MultiLingual是一个很好的例子)

如果你想这样做,或者想改变网站的uri,试着这样做:

<style>
  #flags {
   position:absolute;
   left:97%;
   top:10px;
   width:300px;
   height:30px;
   background-color:transparent;
  }
  #flags a {
   display: block; /* if you want the link to be a block */
  }
</style>
<div id="flags">
<?php
    $actual_link = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
    $strEng = "eng";
    $strIta = "ita";
    $new_link = str_replace($strEng,$strIta, $actual_link);
?>
  <a id="banner" href="<?php echo $new_link; ?>">
    <img src="wp-content/themes/minimable-premium/templates/it-icon-24.png" />
  </a>
  <a href="mydomain.com/bbb/">
    <img src="wp-content/themes/minimable-premium/templates/uk-icon-24.png" />
  </a>
</div>

同样在上面的例子中,你们都忘记了尽量避免内联样式。它是有效的,但是如果你想从中赚钱客户和雇主不会喜欢它;)