→ Using FacetWP With Existing Template Files

Facets are only useful when there’s content to filter upon.

That’s the purpose of a template in FacetWP — to specify which posts to start with, and also how each post item should appear in the list. Below is how to use FacetWP with existing template files.

Template File + CSS Class

If you have an existing Archive (archive.php, archive-product.php, category.php, etc.) or Search (search.php) template, FacetWP could use that file instead. All you need to do is add the CSS class “facetwp-template” to a container element surrounding your WP Loop.

Before:

<?php while ( have_posts() ) : the_post(); ?>
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php endwhile; ?>

After:

<div class="facetwp-template">
<?php while ( have_posts() ) : the_post(); ?>
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php endwhile; ?>
</div>

What about WP Page Templates?

If you’re trying to show facets on an existing WP page template (containing a custom WP_Query) , it probably won’t work out of the box. This is because FacetWP is unable to auto-detect the main query on the page. Don’t worry, it’s possible to tell FacetWP which query to use for filtering. See the following steps:

1. Add a new argument:

<?php
$args = array(
    'post_type' => 'event',
    'posts_per_page' => 10,
    'facetwp' => true, // we added this
);
$query = new WP_Query( $args );

2. Add the facetwp_is_main_query filter (into your theme’s functions.php) to check for the new argument:

<?php
function my_facetwp_is_main_query( $is_main_query, $query ) {
    if ( isset( $query->query_vars['facetwp'] ) ) {
        $is_main_query = true;
    }
    return $is_main_query;
}
add_filter( 'facetwp_is_main_query', 'my_facetwp_is_main_query', 10, 2 );