【问题标题】:PHP output menu items links: array to convert to jsonPHP 输出菜单项链接:要转换为 json 的数组
【发布时间】:2021-07-18 23:51:51
【问题描述】:

我正在尝试从 wp_head 中的自定义导航输出所有链接的列表。我的代码有点工作,但出于某种原因,输出的链接看起来很有趣。

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

我得到:\ / \ / 作为链接而不是://

我是否遗漏了一些明显的东西?

我的代码:

//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' );

【问题讨论】:

    标签: php json wordpress navigation


    【解决方案1】:

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

    json_encode($str, JSON_UNESCAPED_SLASHES);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2016-07-07
      • 2013-06-18
      相关资源
      最近更新 更多