Woocommerce Tax Query that finds the next available product (closest attribute)

Viewed 92

i'm using Ajax and the following function (in functions.php) to pull in a product that has matching attributes. All works well but if there are no products that have an exact attribute (pa_three) then i want it to fetch a product with the next closest pa_three. pa_three is a length.

Any ideas on how i can achieve this?

<?php 

    function example_filter_function(){

        $final_one = $_POST['final_one'];
        $final_two = $_POST['final_two'];
        $final_three = $_POST['final_three'];

        $args = array(
        'orderby' => 'date',
        'post_type' => 'product',
        'posts_per_page' => 1,
        'tax_query' => array(
        'relation' => 'AND',
        array(
        'taxonomy' => 'product_cat',
        'terms' => 1,
        ),
        array(
        'taxonomy' => 'pa_one',
        'field' => 'id',
        'terms' => $final_one
        ),
        array(
        'taxonomy' => 'pa_two',
        'field' => 'id',
        'terms' => $final_two
        ),
        array(
        'taxonomy' => 'pa_three',
        'field' => 'slug',
        'terms' => $final_three
        )
        )
        );

        $query = new WP_Query($args); if ($query->have_posts()) : while ($query->have_posts()): $query->the_post();?>

            <h3><?php the_title();?></h3>

        <?php endwhile; wp_reset_postdata();

            die();
    }

add_action('wp_ajax_myfilter', 'example_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'example_filter_function');

?>
0 Answers
Related