Related posts ordered by taxonomy

Question

On my single post page, I display 4 related posts based on 3 custom taxonomies products, artists, and product-category. Everything works fine with the code below.

BUT: Right now, with this code, the 4 related posts are mixed through all three taxonomies, and ordered by date. I want to order the posts by taxonomy first and then by post date.
I want to display the related posts from productsfirst, and only if there are not enough related posts (4), I want to fill the remaining with related posts from artists, and if there’s still not enough (4), take the remaining related posts from product-category.

Is there a simple way to do that?

1.

$item_cats = get_the_terms( $post_id, array ( 'products', 'artists', 'style' ));
$item_array = array();

2.

if ( $item_cats ) {

    foreach ( $item_cats as $item_cat ) {
        $item_array[] = $item_cat->term_id;
    }
}

3.

if ( ! empty( $item_array ) ) {
    $args = wp_parse_args(
        $args,
        array(
            'ignore_sticky_posts' => 0,
            'posts_per_page'      => $number_posts,
            'post__not_in'        => array( $post_id ),
            'post_type'           => $post_type,
            'tax_query'           => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
            'relation' => 'OR',
                array(
                    'field'    => 'id',
                    'taxonomy' => 'products',
                    'terms'    => $item_array,
                ),
                array(
                    'field'    => 'id',
                    'taxonomy' => 'artists',
                    'terms'    => $item_array,
                ),
                array(
                    'field'    => 'id',
                    'taxonomy' => 'product-category',
                    'terms'    => $item_array,
                ),                  
            ),
        )

    );
0
, , , , HAL2020 3 years 2020-05-02T07:10:30-05:00 0 Answers 85 views 0

Leave an answer

Browse
Browse