• Hi, I’m creating a theme and made custom menu walker class files, but I added an inline <script> in the walker file and it displays the <script>…</script> as many as the number of the file are looped by core like this:

    <script>…</script>
    <script>…</script>
    <script>…</script>
    <script>…</script>
    <script>…</script>

    ‘…’ part is what I intended, but I want to print <script> and </script> tags only once like this way:

    <script> => print only once at the very first time in the loop





    </script> => print only once at the very last time in the loop

    Is it possible to do it in the custom menu walker file?
    Please help me! Thank you.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Andrew Nevins

    (@anevins)

    WCLDN 2018 Contributor | Volunteer support

    Do you want to put your JS code into a JS file and then enqueue that in your functions.php file?

    Thread Starter pinkhare

    (@pinkhare)

    No, it must be added inline in the walker php file directly, because it includes php ID-related code for every looped menu item elements.
    So it must be inside the looped PHP file, and I want for the only <script> open/close tags to render only once but the contents inside should be looped. Could I get any variables related to this walker menu item loop from the core?

    my_custom_walker.php ==> it’s the looped file
    class My_Walker_Nav_Menu extends Walker {
    .
    .
    .

    <script> ==> only once
    jQuery {
    . . . this is the code that should be run on every items here . . .
    jQuery(‘#menu-item-<?php echo $item->ID; ?> …
    }
    </script> ==> only once
    .
    .
    .
    }

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to run my code only once in a custom menu walker file?’ is closed to new replies.