Posted on

Flatsome theme product search results page

The Flatsome theme, when combined with WooCommerce, has a product search results page that can also show posts and pages. That doesn’t work with Relevanssi out of the box, but fortunately can be made to work. The function that adds the functionality is hooked in place, so it’s easy to unhook the default function and replace it with something Relevanssi-friendly.

Like this:

remove_action( 'woocommerce_after_main_content', 'flatsome_pages_in_search_results', 10 );
// Add Pages and blog posts to top of search results if set.
function relevanssi_pages_in_search_results() {
	if ( ! is_search() || ! get_theme_mod( 'search_result', 1 ) ) {
		return;
	}
	global $post;
	if ( get_search_query() ) {
		$args = array(
			'post_type' => 'post',
			's'         => get_search_query(),
		);
		$query = new WP_Query();
		$query->parse_query( $args );
		relevanssi_do_query( $query );
		$posts = array();
		while ( $query->have_posts() ) {
			$query->the_post();
			array_push( $posts, $post->ID );
		}
		$args = array(
			'post_type' => 'page',
			's'         => get_search_query(),
		);
		$query = new WP_Query();
		$query->parse_query( $args );
		relevanssi_do_query( $query );
		$pages = array();
		while ( $query->have_posts() ) {
			$query->the_post();
			$wc_page = false;
			if ( 'page' === $post->post_type ) {
				foreach ( array( 'shop', 'cart', 'checkout', 'view_order', 'terms' ) as $wc_page_type ) {
					if ( $post->ID === wc_get_page_id( $wc_page_type ) ) {
						$wc_page = true;
					}
				}
			}
			if ( ! $wc_page ) {
				array_push( $pages, $post->ID );
			}
		}
		do_action( 'flatsome_products_page_loader' );
		if ( ! empty( $posts ) || ! empty( $pages ) ) {
			$list_type = get_theme_mod( 'search_result_style', 'slider' );
			if ( ! empty( $posts ) ) {
				echo '<hr/><h4 class="uppercase">' . __( 'Posts found', 'flatsome' ) . '</h4>' . do_shortcode( '[blog_posts columns="3" columns__md="3" columns__sm="2" type="' . $list_type . '" image_height="16-9" ids="' . implode( ',', $posts ) . '"]' );
			}
			if ( ! empty( $pages ) ) {
				echo '<hr/><h4 class="uppercase">' . __( 'Pages found', 'flatsome' ) . '</h4>' . do_shortcode( '[ux_pages columns="3" columns__md="3" columns__sm="2" type="' . $list_type . '" image_height="16-9" ids="' . implode( ',', $pages ) . '"]' );
			}
		}
	}
}
add_action( 'woocommerce_after_main_content', 'relevanssi_pages_in_search_results', 10 );

Add this to your Flatsome child theme functions.php, and the search results will show Relevanssi-generated results for posts and pages.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.