OnFocus javascript command causing WordPress to crash

I’m tweaking a WordPress theme and I’m trying to clear the search field on focus, but when I add the following code, I get the white screen of death. The actual javascript function seems to be what’s killing it because if I run this PHP script with an empty onfocus=”” command, everything is fine.

    add_filter('wp_nav_menu_items','add_search_box', 10, 2);
    function add_search_box($items, $args) {
if( $args->theme_location == 'primary' ) {
    $items .= '<li id="omc-header-search">              
                    <span id="omc-search-overlay">'. __('Search', 'gonzo') .' &rarr;</span>
                    <form method="get" id="desktop-search" class="omc-search-form" action="'.get_bloginfo('url').'/">
                        <input type="text" class="omc-header-search-input-box" value="Search" onfocus="if(this.value == 'Default text') { this.value = ''; }" name="s" id="fffff">
                        <input type="submit" class="omc-header-search-button" id="searchsubmit" value="">
                    </form>
                </li>';

return $items;

}

I have no idea why this would be causing the whole thing to crash.

Related posts

Leave a Reply

2 comments

  1. A white page usually indicates a PHP fatal error or syntax error.
    In this case, there’s a couple different errors:

    • You have not closed the { from your if() statement
    • Your long string of text has embedded quotes ' that are not properly escaped.

    You’re also inconsistant in what the default text in the field should be.

    • You’re setting it to "Search" with value="Search"
    • …but you’re clearing it only if it equals "Default text".

    If you fix the PHP syntax errors, and update Default text to Search, it should work.

    Like this:

    add_filter('wp_nav_menu_items','add_search_box', 10, 2);
    function add_search_box($items, $args) {
        if( $args->theme_location == 'primary' ) {
            $items .= '<li id="omc-header-search">              
                <span id="omc-search-overlay">'. __('Search', 'gonzo') .' &rarr;</span>
                <form method="get" id="desktop-search" class="omc-search-form" action="'.get_bloginfo('url').'/">
                <input type="text" class="omc-header-search-input-box" value="Search" onfocus="if(this.value == 'Search') { this.value = ''; }" name="s" id="fffff">
                <input type="submit" class="omc-header-search-button" id="searchsubmit" value="">
                </form>
                </li>';
        }
        return $items;
    }
    
  2. Try escaping the quotes inside the onfocus:

    onfocus="if(this.value == 'Default text') { this.value = ''; }"
    

    When echoed by php the backslash will disappear and the script will look like you want.