Display products for a category, sorted by post_excerpt

I’d like to display a list of products for a certain category, sorted by the post_excerpt.
The original code I used was this:

$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array( 'my-product-category' ),
            'operator' => 'IN'
        )
    ),
    'orderby' => 'post_excerpt', 
    'order' => 'ASC'
);

$loop = new WP_Query( $args );    

This displays the products, but the orderby is ignored in a taxonomy query. So I’ve changed the query to:

Read More
$args = array( 
            'post_type' => 'product', 
            'orderby' => 'post_excerpt', 
            'order' => 'ASC',
            'product_cat' => 'My Product Category',
            'post_status' => 'publish'
        );
$loop = new WP_Query( $args ); 

The products are displayed, but the orderby clause is still ignored.

Related posts

Leave a Reply

2 comments

  1. If you take a look at the WordPress Codex ‘post_excerpt’ is not a valid parameter for the ‘orderby’ parameter

    For this reason it cannot be done through WP_Query(). If you don’t mind, why are you trying to sort by post_excerpt in the first place?

  2. Now, you can use filter posts_orderby.

                add_filter('posts_orderby', function($orderby) {
                    return str_replace(
                        'wp_posts.post_modified',
                        'wp_posts.post_excerpt',
                        $orderby);
                }, 10, 3);
                $custom['orderby'] = 'modified';
                new WP_Query( $custom );