1

I'm trying to use FancyBox to open a lightbox-style popup with the searchform.php, when the user clicks on the search icon.

The setup:

  • in header.php I have a link element which will show only the search icon;
  • in script.js I bind the click on the search icon to fancybox and I open the modal/lightbox iframe with the content of searchform.php;

The problem: the iframe doesn't load the WordPress environment so nothing is working. How can I use fancybox and still have access to the WP functions?

The next step will be to show the results of the search in the same iframe using AJAX.

The code:

// header.php
<a id="search-label" data-fancybox-type="iframe" href="<?php echo get_template_directory_uri(); ?>/searchform.php"></a>

// searchform.php
<div class="search-container">
    <p>This is a test</p>
    <form action="<?php echo home_url( '/' ); ?>" method="get">
        <fieldset>
            <input type="text" class="notv" id="search" name="s" value="<?php the_search_query(); ?>" />
        </fieldset>
    </form>
</div>  

// script.js
jQuery(document).ready(function($) { 
        $("#search-label").click(function () {
            $('.search-container').toggle();
            $('#search-label').fancybox({
                maxWidth    : 800,
                maxHeight   : 600,
                fitToView   : false,
                width       : '70%',
                height      : '70%',
                autoSize    : false,
                closeClick  : false,
                openEffect  : 'none',
                closeEffect : 'none'
            })
        })
    }); 
2

The easiest way:

  1. create a page template that only includes the search form (get_search_form())
  2. create a page and assing the template
  3. In the href attrib of the iframe, instead of put the url for searchform.php put the url of the page

Pretty easy, but you need a query to get the page. A more performant way is to use fancybox without iframe, but via ajax, e. g.:

<?php
$url = add_query_arg( array('action'=>'show_search_form'), admin_url('admin-ajax.php') );
?>
<a id="search-label" href="<?php echo $url; ?>"></a>

Then use ajax API to call get_search_form() inside the ajax action, e. g.:

add_action( 'wp_ajax_show_search_form', 'mytheme_show_search_form' );
add_action( 'wp_ajax_nopriv_show_search_form', 'mytheme_show_search_form' );

function mytheme_show_search_form() {
   get_search_form();
   exit();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.