Cray
Cray

Reputation: 5513

Sort WooCommerce variations by custom date field

I want to display a list of upcoming concerts. Every concert has two attributes: date and location.

I've tried to show the next concerts by display all variations. This is what I've done so far:

<?php
    global $woocommerce, $product, $post, $re_wcvt_options;
    $available_variations = $product->get_available_variations();
    $attributes = $product->get_attributes();
?>
<ul>
    <?php foreach ($available_variations as $prod_variation) : ?>
        <?php
            // get some vars to work with
            $post_id = $prod_variation['variation_id'];
            $post_object = get_post($post_id);
        ?>
        <li>
        <?php foreach ($prod_variation['attributes'] as $attr_name => $attr_value) : ?>
            <?php
                // Get the correct variation values
                if (strpos($attr_name, '_pa_')){ // variation is a pre-definted attribute
                    $attr_name = substr($attr_name, 10);
                    $attr = get_term_by('slug', $attr_value, $attr_name);
                    $attr_value = $attr->name;
                } else { // variation is a custom attribute
                }
                echo $attr_value;
            ?>
        <?php endforeach;?>
        </li>
    <?php endforeach;?>
</ul>

The proplem with this solution is that it only works within a product and only for one product. I couldn't show a list of multiple concerts (products) with differnt locations and dates (variations).

So I tried to use the loop to display the products/concerts and sort by a custom field with a date in it.

I've done that for a simple custom post type in the past. This was the solution for that:

<?php
$today_query = date ('Ymd');
$args = array(
    'post_type'              => array( 'concert' ),
    'posts_per_page'         => '10',
    'meta_key' => 'date',
    'meta_compare' => '>=',
    'meta_value' => $today_query,
    'orderby' => 'meta_value',
    'order' => 'ASC',
);
$query = new WP_Query( $args ); ?>

The code orders the posts by meta field and shows only concerts in the future. The only thing I don't understand is how I could use the meta fields from a single variation?!

Does anyone have a solution for this?

Upvotes: 0

Views: 1744

Answers (1)

pearcake
pearcake

Reputation: 346

Try to use pre_get_posts hook

add_action( 'pre_get_posts', 'sort_products' );

function sort_products( $query )
{
    // If inside dashboard, skip sorting
    if (is_admin()){
        return;
    }
    // Check of query have woocommerce post type
   if (is_post_type_archive('product')){
        $query->set('meta_key', 'date');
        $query->set('meta_compare' , '>=');
        $query->set('meta_value' , time());
        $query->set('orderby', 'meta_value');
    }
    return $query;
}

Upvotes: 1

Related Questions