PHP output restaurant menu items: converting array to JSON format

I'm encountering an issue while trying to display a list of links from my custom navigation in wp_head. Although my code is somewhat functional, the outputted links appear distorted.

Expected link: https://example.com/sample-page/

Actual result: \ / \ / displayed instead of ://

I wonder if I'm overlooking something obvious?

Here's the code snippet:

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

Answer №1

The output matches expectations perfectly. When using the json_encode function, it automatically escapes forward slashes by adding a backslash before them. This is especially useful when embedding the JSON data in script tags. If you prefer not to have the forward slashes escaped, you can instruct PHP to omit them by including the flag:

json_encode($str, JSON_UNESCAPED_SLASHES);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

posting data and redirecting fails when using an ajax button

I am encountering an issue where I click a button on a page to navigate to another page with posted data, but it is redirecting without posting anything. Both $_POST and $_SESSION variables are empty. Below is my ajax function: function ajax4(Div_Submit, ...

Retrieving the value of an array from a JSON data structure

I am working with the object shown below to extract the desired output. The result will be a new object that represents the final output. var data = { Customer: { Name: "emp1", Departments: [ {Departme ...

Retrieving JSON information using Angular.js

I have been struggling to fetch JSON data from a URL using the code provided below. Unfortunately, it seems that the data is not being populated as expected. Despite trying various approaches, nothing seems to work out successfully. Below is the basic code ...

Ways to display the main image on a blog post

This piece of code is designed for displaying the relevant post associated with wp_ai1ec_events function display_event($atts ) { global $wpdb; $event = $wpdb->get_results("SELECT * FROM wp_ai1ec_events ORDER BY start"); ...

Obtain the key's value from a JSON object that is nested within another

Managing a complex data structure is crucial in programming. How can I efficiently retrieve specific values using known keys from this nested data? Take, for instance: var data = { code: 42, items: [{ id: 1, category: [{ ...

Tips for showing menu only when a user scrolls on your WordPress site

I've been working on creating an effect where the menu stays hidden until the user starts scrolling. However, I can't seem to figure out why my code is not producing the desired effect. Here is the jQuery code snippet I am using: <script src= ...

The issue of parsing JSON data into objects

Consider an array scenario where the size is 1: the json data received will not contain [], for example: {"firstname":"tom"} On the other hand, when the size exceeds 1, the data received will include [], like this: [{"firstname":"tom"},{"firstname":"rob ...

Leveraging Postmark in PHP applications

Hey there, I'm currently diving into the world of PHP and Postmark in an effort to set up a form submission that sends data to my email. While I've managed to get the email functionality working, I'm encountering an issue with redirecting to ...

Difficulty encountered when analyzing a correctly structured JSON file in Python

I am having trouble decoding a JSON file using Python3.6 and the json module. An error that I keep encountering is: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) Despite trying both json.load ...

Storing JSON data for retrieval using Ajax request

Apologies if this is a silly question. I am working with a JSON data file and I want to retrieve it using AJAX. Since the data is already serialized, do I still need an action result to return JSON? Or not? Is it okay to store the JSON file within my pro ...

Processing PHP response while waiting for jQuery AJAX call

I utilized an ajax function to transmit data. Within the PHP process, I executed phpmailer to send emails by using smtp gmail. The procedure proceeded smoothly, however, there are instances where I require informing the user to wait for the ongoing process ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...

LibGDX's latest project featuring a vibrant yellow warning triangle

Recently, I embarked on a new endeavor with LibGDX. While normally I overlook the presence of yellow warning triangles in my projects, this time it has become somewhat bothersome. Is there a way to address this issue? Here is a visual representation: ...

Modify an entire column rather than a single row

Is it possible to update a specific column instead of an entire row in a table? For example, is something like this valid: $laninpstmt = $db->prepare ("UPDATE table SET column_name WHERE id = :allids"); $laninpstmt->bindParam(':allids', ...

Substitute terms in web address

Can you assist me with replacing words in URLs/links for WordPress? For example, if there is a mention of "red" in my article, I want it to be replaced by "orange," but only in the URLs/links and not anywhere else in the article. Here are the rules: - Rep ...

PHP process encountered an issue loading the gettext module, causing it to be inaccessible

I have encountered a problem with the gettext module in PHP that remains unsolved despite trying various solutions. Every time I attempt to use the gettext module, I receive the following warning message: PHP Warning: PHP Startup: Unable to load dynamic ...

Converting a JSON object to a string in Java

I am working with a JSON file and looking to convert it from JSON to string using the org.simple.json library. { "header": { "IssuerID": "000141", "AuthenticationID": "e07020c0d040a050a0808099", "AuthenticationDateTime ...

Java - RESTful API endpoint that serves images when available and JSON data when images are not available

I am currently working on incorporating a mobile front-end using the Ionic Framework along with the $cordovaFileTransfer plugin. My focus is on fetching and uploading a person's Profile Photo. Uploading the photo is functioning properly, but I am enco ...

Creating a Dynamic Tree View Component in AngularJS Using JSON Data

I am new to AngularJS and I need help creating a TreeView Structure from a JSON Object. Here is an example of my Return JSON Object: var categoryTree = [{Name:'Item1', Childnodes : {}, id: 1}, {Name:'Item2', Childnod ...

Using HTML URL parameter in PHP code

Hi there, I'm new to using PHP and would appreciate any help you can provide. I'm facing an issue with passing a URL parameter from an HTML page (mywebsite.com/f.html?survey_id=5d86055f35bf41f3a35f2c779fc478dc) to a PHP script that should save t ...