1

我有:

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*')";

怎么做?

4

2 回答 2

1

好吧,我想我会尝试使用 PHPDomDocument将 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;
于 2013-09-13T13:08:28.057 回答
0

将以下内容添加到您的 functions.php 文件中,该文件使用 wp_nav_menu_objects 过滤器挂钩连接到 WP Core。

function modify_nav_url($items) {
    $old_url = "http://link*";
    $new_url = "javascript:myfunc('http://link*')";

    foreach($items as $item){
        $item->url = str_replace($old_url, $new_url, $item->url);
    }
    return $items;
}
add_filter('wp_nav_menu_objects', 'modify_nav_url');

来源:https ://wordpress.stackexchange.com/questions/137732/change-menu-items-url

于 2021-09-08T23:21:48.950 回答