• Aucun résultat trouvé

We are going to introduce a little bit of templating here. Although we could simply concatenate variables from our search results, it's more readable and maintainable to use some kind of templates for formatting. We are going to create one additional sub-directory in our plugin's directory: tpls/, short for "templates". In it will we store our template files that will be used to format our search results. We're going to use three different templates, designated with a .tpl extension:

1. A template to use when there are no search results: no_results.tpl. 2. A template to format each individual search result: single_result.tpl. 3. A template which will contain the individual results: results_container.tpl. This is not traditional PHP per se, but it does represent some valuable principles garnered from other MVC applications and it can be a great way to create customizable layouts. We will provide sample text for each template before we show you how to parse them. The name of the game here is placeholders. We will denote placeholders by flanking a word with "[+" and "+]". Let's take a look at some examples so you can see what we mean.

The tpls/single_result.tpl will make use of a couple placeholders:

<li>

<a href="[+permalink+]">[+post_title+]</a>

</li>

The tpls/results_container.tpl will wrap the collective individual results.

It will only use a single "[+content+]" placeholder to denote where the individual results will appear:

<div id="ajax_search_results">

<ul>

[+content+]

</ul>

</div>

Lastly, tpls/no_results.tpl contains no placeholders, just a message to display if no results were found:

<div id="ajax_search_results">

<p>No results found.</p>

</div>

Can you see how each result is formatted as a list item, and then the collection of results is formatted into an unordered list?

Previously, we showed you the sprintf() function, which makes use of %s as a type of placeholder. sprintf() can even swap the order of the arguments by using placeholders such as %1$s and %2$s—look at the manual page under "argument swapping" for more information. However, this is hard to read. It is not clear what value might be substituted into %s, whereas a placeholder such as "[+permalink+]"

gives you a good idea of what will replace the placeholder.

Now that we have our templates set up, how do we parse them? We are going to create a simple function that relies on PHP's str_replace(). To get the template files as raw strings (without executing any PHP in them), we load them using PHP's file_get_contents() function.

When we put it all together, our ajax_search_results.php file ends up looking like the following:

<?php /**

* This file is an independent controller, used to query the WordPress database

* and provide search results for Ajax requests.

*

* @return string Either return nothing (i.e. no results) or return some formatted results.

*/

if (!defined('WP_PLUGIN_URL')) {

// WP functions become available once you include the config file require_once( realpath('../../../').'/wp-config.php' );

}

// No point in executing a query if there's no query string if ( empty($_GET['s']) )

{

exit;

}

$max_posts = 3; // Number of results to show

$WP_Query_object = new WP_Query();

$WP_Query_object->query(array('s' => $_GET['s'], 'showposts' => $max_

posts));

// If there are no results...

if (! count($WP_Query_object->posts) ){

print file_get_contents( 'tpls/no_results.tpl');

exit;

}

// Otherwise, format the results

$container = array('content'=>''); // define the container's only placeholder

$single_tpl = file_get_contents( 'tpls/single_result.tpl');

foreach($WP_Query_object->posts as $result) {

$result->permalink = get_permalink($result->ID);

$container['content'] .= parse($single_tpl, $result);

}

* A simple parsing function for basic templating.

*

* @param $tpl string A formatting string containing [+placeholders+]

* @param $hash array An associative array containing keys and values e.g. array('key' => 'value');

* @return string Placeholders corresponding to the keys of the hash will be replaced with the values the resulting string will be returned.

While testing this, it's useful to refresh a page that navigates to it directly, just remember to include a valid search term: http://yoursite.com/wp-content/

plugins/live-search/ajax_search_results.php?s=something.

You may have noticed that we manipulated the search results as objects in PHP, using arrow notation:

$result->new_value = 'something';

This was as opposed to an associative array:

$result['new_value'] = = 'something else';

Our parse() function can reliably iterate over the properties of an object in the same way as the elements of an associative array.

Although building our own template parsing functions like this is slower and it may be more confusing for you the first time you set it up, it is much easier to maintain and change over a longer term. Any inebriated frontend designer can make alterations to the template files contained in the tpls/ directory without fear of breaking some delicate PHP concatenation. The worst thing that could happen when using our templating system is that a placeholder is unrecognized and comes out the other end unparsed.

Save your work and give this one final test. Refresh your home page and try

searching for a word. You should get the Ajax search results to appear directly below your search form.

Summary

We've come a long way. We have learned about how Ajax works and we've learned how to tie into jQuery and how to debug some JavaScript. We have also learned how to use PHP library classes with static functions in our plugins and how to tie into the WordPress application from the backdoor. In order to pull this off, we have created a total of nine files:

• ajax_search_results.php

• css/live-search.css

• includes/dynamic_javascript.php

• includes/LiveSearch.php

• index.php

• tests/Test.php

• tpls/no_results.tpl

• tpls/results_container.tpl

• tpls/single_result.tpl

We have constructed a working Ajax search, but as you may have noticed, it was fairly complex to set up, and even after all that work, it is still fairly primitive. The goal here was to teach you how to construct a plugin that relied on Ajax; if you want a full-featured Ajax search for your site, try downloading an existing plugin.

One example is Dave's WordPress Live Search (http://wordpress.org/extend/

plugins/daves-wordpress-live-search). We think our code is cleaner, but Dave's plugin has a lot of customizable options and it handles edge cases that are beyond the scope of this chapter.

Next, we will dive into the world of WordPress widgets. The next chapter will expand our understanding of PHP classes by introducing us to some real object-oriented code, and everything we learned about Ajax will come in handy. Get ready for some widgets!