PHP 输出菜单项链接:要转换为 json 的数组

PHP output menu items links: array to convert to json

我正在尝试从 wp_head 中的自定义导航中输出所有 link 的列表。我的代码有点儿用,但出于某种原因,link 的输出看起来很滑稽。

我期待得到 https://example.com/sample-page/

我得到:\ / \ / 作为 link 而不是 ://

我是不是遗漏了什么明显的东西?

我的代码:

//OUTPUT MENU
  function get_nav_items() {

    $menu_slug_to_retrieve = 'my-custom-menu';
    $locations             = get_nav_menu_locations();
    $menu                  = wp_get_nav_menu_object( $locations[ $menu_slug_to_retrieve ] );
    $menu_items            = wp_get_nav_menu_items( $menu->term_id );
    $menu_items_json       = array(); // Prepare the array to convert to json
 
    // Loop it
    if ( $menu_items ) {
 
       foreach ( $menu_items as $item ) {
           $menu_items_json[] = array( 'url' => $item->url );
       }
 
       $html = sprintf(
           '<script type="application/ld+json" id="custom-json">%s</script>',
           json_encode( $menu_items_json )
       );
 
       echo $html;
    }
  }
  add_action( 'wp_head', 'get_nav_items' );

这是非常符合预期的输出。 json_encode 所做的是,它通过在前面加上反斜杠来转义所有正斜杠。如果您将它包含在 script 元素中,这会很方便。如果你不想要转义的正斜杠,你可以通过添加这个标志来告诉 php:

json_encode($str, JSON_UNESCAPED_SLASHES);