0

I created a custom query in my template to show certain products. I would like to add a sort feature for pricing ascending and descending but have not had any luck. Here is my code on my template:

<?php
global $wp;

$args = array(
    'post_type'      => 'product',
    'meta_query'     => array(
    array( 'key' => 'availability', 'value' => 'available' )
        ),
    'orderby'        => 'meta_value_num',// rand,
    'meta_key'       => '_price',// added for orderby
    'order'          => 'asc',// added for orderby
    'posts_per_page' => -1
);

$query = new WP_Query( $args );

if ( $query->have_posts() ) : ?>

    <ul class="products">
        <?php while ( $query->have_posts() ) : $query->the_post(); ?>

        <?php woocommerce_get_template_part( 'content', 'product' ); ?>

        <?php endwhile; // end of the loop. ?>
    </ul>
    <?php endif;
        wp_reset_postdata();
    ?>

I added the orderby, meta_key and order to test and see if the query would sort and it will. I cannot figure out how to get it to sort like the default "Shop" page works. I have also tried this that I had gotten from another post and it just won't work:

add_shortcode( 'minimum_stock', 'minimum_stock_shortcode' );

function minimum_stock_shortcode( $atts ) {

global $woocommerce_loop;

// Attributes 
$atts = shortcode_atts(
    array(
    'limit'                 => '40',
    'columns'               => '5',
    'orderby'               => 'date',
    'order'                 => 'desc',
    //'category'              => '',
    'cat_operator'          => 'IN'
    //'stock'                 => ''
    ), $atts );

if ( ! $atts ) {
    return '';
}

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

// Default ordering args
$ordering_args = WC()->query->get_catalog_ordering_args( $atts['orderby'], $atts['order'] );
$orderby = 'date';
$order = 'desc';
if ( isset( $_GET['orderby'] ) ) {
    $getorderby = $_GET['orderby'];
}
if ($getorderby == 'date') {
    $orderby = 'date';
    $order = 'desc';
} elseif ($getorderby == 'price_desc') {
    $orderby = 'meta_value_num';
    $order = 'desc';
    $meta_key = '_price';
} elseif ($getorderby == 'price') {
    $orderby = 'meta_value_num';
    $order = 'asc';
    $meta_key = '_price';
}

$args = array(
  'post_type'             =>  'product',
  //'post_status'           => 'publish',
  //'ignore_sticky_posts'   => 1,
  'posts_per_page'        => $atts['limit'],
  'orderby'               => $orderby, // $ordering_args['orderby'],
  'order'                 => $$order, // $ordering_args['order'],
  'meta_key'              => $meta_key,
  'paged'                 => $paged,
  'meta_query'            => array(
                              array( 'key' => 'availability', 'value' => 'available' )
                              )
);


if ( isset( $ordering_args['meta_key'] ) ) { 
   $args['meta_key'] = $ordering_args['meta_key']; 
}

ob_start();

$products = new WP_Query( $args );

$woocommerce_loop['columns'] = $atts['columns'];

if ( $products->have_posts() ) : ?>

<div style="width:100%;">
    <div style="float:right">
        <form class="woocommerce-ordering" method="get">
            <select name="orderby" class="orderby">
                <?php
                    $catalog_orderby = apply_filters( 'woocommerce_catalog_orderby', array(
                        'date'        => __( 'Sort by latest', 'woocommerce' ),
                        'price'       => __( 'Price / Lowest to Highest', 'woocommerce' ),
                        'price_desc'  => __( 'Price / Highest to Lowest', 'woocommerce' )
                    ) );

                    foreach ( $catalog_orderby as $id => $name )
                        echo '<option value="' . esc_attr( $id ) . '" ' . selected( $getorderby, $id, false ) . '>' . esc_attr( $name ) . '</option>';
                ?>
            </select>
            <?php
                // Keep query string vars intact
                foreach ( $_GET as $key => $val ) {
                    if ( 'orderby' === $key || 'submit' === $key )
                        continue;

                    if ( is_array( $val ) ) {
                        foreach( $val as $innerVal ) {
                            echo '<input type="hidden" name="' . esc_attr( $key ) . '[]" value="' . esc_attr( $innerVal ) . '" />';
                        }

                    } else {
                        echo '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( $val ) . '" />';
                    }
                }
            ?>
        </form>
    </div>
</div>
<div style="clear:both;"></div>

<div class="woocommerce">
    <?php woocommerce_product_loop_start(); ?>
    <ul class="products">
        <?php while ( $products->have_posts() ) : $products->the_post(); ?>

            <?php wc_get_template_part( 'content', 'product' ); ?>

        <?php endwhile; // end of the loop. ?>
    </ul>
    <?php woocommerce_product_loop_end(); ?>
</div>
<?php endif; 
if($products->max_num_pages>1) {
?>

<nav class="woocommerce-pagination"> 

<?php echo paginate_links( apply_filters(
        'woocommerce_pagination_args', array( 
            'base'      => esc_url( str_replace( 999999999, '%#%', remove_query_arg( 'add-to-cart', get_pagenum_link( 999999999, false ) ) ) ), 
            'format'    => '', 
            'current'   => max( 1, get_query_var( 'paged' ) ), 
            'total'     => $products->max_num_pages, 
            'prev_text' => '&larr;', 
            'next_text' => '&rarr;', 
            'type'      => 'list', 
            'end_size'  => 3, 
            'mid_size'  => 3 
        )
    )       
);

?>

</nav>

<?php }

woocommerce_reset_loop(); 
wp_reset_postdata();

$return = '<div class="woocommerce columns-' . $atts['columns'] . '">' . ob_get_clean() . '</div>';

// Remove ordering query arguments 
WC()->query->remove_ordering_args();

return $return; 
}

I think take all of the previous stuff out of my template and add this:

<?php echo do_shortcode( '[minimum_stock]' ); ?>

I still can't get anything to work. Any help would be greatly appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.