TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
Victoria wordpress
1. Focusing Search
Improving the built in search
functionality of WordPress
By Flynn O’Connor / @thoronas
2. My name is Flynn O’Connor
• Developing WordPress themes for 4
years.
• Lead developer at Forge and Smith
• Slides available here:
http://slidesha.re/VTYhJ4
4. How WordPress Search work?
When you use the default WordPress search
form it’s the equivalent of this:
$query = new WP_Query( ’s’ => ‘keyword’ );
5. Take Control
Inputs added to the form can control the
query. But they must match the
corresponding query parameters.
6. Doing it wrong
Neither of these will work automatically:
• <input name="post-type" type="hidden" value=”listing" />
• <input name="postType" type="hidden" value=”listing" />
It’s like trying to do:
$query = new WP_Query( ’post-type’ => ‘listing' );
7. The Right Way
• <input name="post_type" type="hidden" value=”listing" />
Equivalent of:
$query = new WP_Query(
’s’ => ‘keyword’,
‘post_type’ => ‘listing’ );
The Search query is altered to only search events
posts.
8. Give users control
Allow users to search within a single
category with a WordPress core function.
Example:
<?phpwp_dropdown_categories(); ?>
Outputs:
<select id="cat" name="cat">
<option value="1" class="level-0">Uncategorized</option>
<option value="4" class="level-0">Featured</option>
</select>
11. Form inputs are helpful for adding simple
search parameters. But for multiple choice
elements we need more control.
The following won’t work:
$args = array (
‘custom_tax’ => array(7, 8)
);
$query = new WP_Query( $args );
12. Say hello to my little friend
pre_get_posts
This action will alter the query before it is
run. With this you can do complicated
search queries involving taxonomies and
meta values.
14. Changing the structure
If you allow search for multiple post types
sometimes you will need to have different
structure/layout for your content.
15. get_post_type( )
Use this to load different templates based on
the post types searched.
while ( have_posts() ) : the_post();
get_template_part( ’content', get_post_type() );
endwhile;
16. The elephant in the room
You can sort the results :
• Date
• Name
• Menu Order
• Random
The major problem with the built in
WordPress search: search results can’t be
sorted by relevance to the search term.
20. Plays nice with others
Because we are using pre_get_posts and
passing valid query variables via form
elements all of our custom search queries
will work with Relevanssi right out of the
box.