php – Adding search bar/form to a custom HTML navigation in WordPress using get_search_form() function-ThrowExceptions

Exception or error:

My problem is that I built the navigation menu inside the ‘top’ section in the widgets area in WordPress (which is perhaps a mistake, as I can’t add php in there).
Assume my menu is built this way:

<nav>
<div class="title-and-logo">...</div>
<div class="menu-links">...</div>
<div class="search-bar">   </div>
</nav>

The relevant css:

nav{
display: flex;
}

I need to add the search bar into the .search-bar div. My solution is to move the whole nav menu out of widgets area and into functions.php. (I am not very comfortable with PHP yet, that is why I am reluctant to mess around with it).

My question: is there a way to add the search bar generated by get_search_form() into the section with class=”search-bar” without needing to remove my code somewhere that allows PHP?

Or: can I generate a normal search bar using HTML without needing to use the get_search_form() provided by WordPress? (but maybe the search function of WordPress is better?).

Any help is appreciated. You can suggest javascript and jquery fixes too.

How to solve:

You could create a custom widget area in your functions.php for your top nav like so:

<?php
/**
 * Register our sidebars and widgetized areas.
 *
 */
function my_custom_widget_area_init() {

    register_sidebar( array(
        'name'          => 'Top Nav - Search',
        'id'            => 'top_nav_search',
        'before_widget' => '',
        'after_widget'  => '',
        'before_title'  => '',
        'after_title'   => '',
    ) );

}
add_action( 'widgets_init', 'my_custom_widget_area_init' );
?>

Then you adjust your theme to display the widget:

<nav>
    <div class="title-and-logo">...</div>
    <div class="menu-links">...</div>
    <?php if ( is_active_sidebar( 'top_nav_search' ) ) : ?>
    <div class="search-bar"><?php dynamic_sidebar( 'top_nav_search' ); ?></div>
    <?php endif; ?>
</nav>

###

Okay so I had a very specific problem which I doubt anyone else would have, but anyway, here is how I solved it:

I already had a plugin installed called ‘widget shortcode’ which transforms any widget I have into a shortcode that can be used inside text areas on the website.

A bit irrelevant but recall that I also had my navigation placed inside an HTML widget (but I was not using it as a shortcode, it was placed directly into the ‘top widget area’.)

So all I had to do was get the shortcode of the search widget (as we have a search widget by default on WordPress) and insert it inside the HTML of my Nav.

Problem: turns out we can’t put shortcodes by default inside html widgets. Solution: place one line code in functions.php that would allow us to do so. Problem solved.

Leave a Reply

Your email address will not be published. Required fields are marked *