Search using WP_Query

Question

I’m using the following WP_Query within my search.php template in order to only search the ‘products’ custom post type. For some reason, its returning other post types with some search terms.

Any Ideas where I’m going wrong?

<?php global $query_string; ?>

<?php $query_args = explode("&", $query_string); ?>

<?php $search_query = array( 'post_type' => 'products', 'posts_per_page' => 12, 'paged' => $paged, 'orderby' => 'name', 'order' => 'ASC' ); ?>

<?php foreach($query_args as $key => $string) {

    $query_split = explode("=", $string);

    $search_query[$query_split[0]] = urldecode($query_split[1]);

} ?>

<?php $search = new WP_Query($search_query); ?>

<?php if ( $search->have_posts() ) : while ( $search->have_posts() ) : $search->the_post(); ?>

<div class="product">
    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
        <section>

            <?php if( get_field('product_image') ) { ?>

                <?php $product_image = get_field('product_image'); ?>
                <img src="<?php echo $product_image['sizes']['thumbnail']; ?>" alt="<?php echo $product_image   ['alt']; ?>" >

            <?php } else { ?>

                <img src="<?php bloginfo('template_url'); ?>/images/fallback-image.png" alt="Product image coming soon.">

            <?php } ?>

            <h2><?php trimmed_title('...', 22); ?><br /><span><?php the_field('reference_number'); ?></span></h2>

        </section>
    </a>
</div>

<?php endwhile; else: ?>

<p>Sorry, no products matched your search criteria.</p>

<?php endif; ?> 
0
Matthew Haigh 8 years 2013-12-12T07:07:18-05:00 0 Answers 80 views 0

Leave an answer

Browse
Browse