0

I have created a WooCommerce search plugin. It fetches products, however it only displays the products as one per row.

How can I amend my query to display 3 products per row? Here is the function:

 function realtime_product_search_enqueue_scripts() {
    wp_enqueue_script('realtime-product-search', plugin_dir_url(__FILE__) . 'realtime-product-search.js', array('jquery'), '1.0', true);
    wp_localize_script('realtime-product-search', 'realtime_product_search_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'realtime_product_search_enqueue_scripts');

function perform_product_search() {
    $searchQuery = isset($_POST['search_query']) ? sanitize_text_field($_POST['search_query']) : '';
    $categoryFilter = isset($_POST['category_filter']) ? $_POST['category_filter'] : array();

    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        's' => $searchQuery,
    );

    if (!empty($categoryFilter)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $categoryFilter,
                'operator' => 'IN',
            ),
        );
    }

    $loop = new WP_Query($args);
    $count = 0;

    if ($loop->have_posts()) {
        echo '<div class="product-row">'; // Start the product row
        while ($loop->have_posts()) : $loop->the_post();
            if ($count % 3 === 0 && $count > 0) {
                echo '</div><div class="product-row">'; // Close previous row and start a new row after every 3 products
            }
            wc_get_template_part('content', 'product');
            $count++;
        endwhile;
        echo '</div>'; // Close the last product row
    } else {
        echo __('No products found');
    }

    wp_reset_postdata();

    die();
}

1 Answer 1

0

Your query does not determine how many show per row; you'd use CSS to accomplish that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.