如何在wp_nav_menu中修改url?

时间:2013-09-13 11:24:24

标签: wordpress wordpress-theming

我有:

wp_nav_menu(array(
            'theme_location' => 'header-menu',
            'depth' => 1,
            'container' => 'div',
            'link_before'     => '',
            'link_after'      => '',
        )
);

这给了我:

<ul>
    <li class="page_item page-item-1">
        <a href="http://link1">link1</a>
    </li>
    <li class="page_item page-item-2">
        <a href="http://link2">link2</a>
    </li>
    <li class="page_item page-item-3">
        <a href="http://link3">link3</a>
    </li>
</ul>

但我想在以下链接中替换url:

"http://link*" 

为:

"javascript:myfunc('http://link*')";

怎么做?

1 个答案:

答案 0 :(得分:1)

好吧,我以为我可以使用PHP DomDocument来解析HTML作为字符串并替换href属性的值。

$content = '
    <ul>
        <li class="page_item page-item-1">
            <a href="http://link1">link1</a>
        </li>
        <li class="page_item page-item-2">
            <a href="http://link2">link2</a>
        </li>
        <li class="page_item page-item-3">
            <a href="http://link3">link3</a>
        </li>
    </ul>
';

// New Dom Object
$dom = new DomDocument;

// Load $content as string
$dom->loadHTML($content);

// Get only a elements
$elements = $dom->getElementsByTagName('a');

// Loop through each a element and get it's href value
for ($n = 0; $n < $elements->length; $n++) {
    $item = $elements->item($n);

    // Get old href val
    $old_href = $item->getAttribute('href');

    // New href val
    $new_href = 'javascript:myfunc(\''.$old_href.'\')';

    // Replace old href with new
    $content = str_replace($old_href,$new_href,$content);
}

// Print results
echo $content;