I have a custom post type course which is linked via meta_key _course_product to Woocommerce product. I need to order those courses (post type course) by product price (meta_key _price) within the action pre_get_posts

THE custom post type course args.

$args = (
    'labels' => array (
        'name' => __('Courses', 'academy'),
        'singular_name' => __( 'Course', 'academy' ),
        'add_new' => __('Add New', 'academy'),
        'add_new_item' => __('Add New Course', 'academy'),
        'edit_item' => __('Edit Course', 'academy'),
        'new_item' => __('New Course', 'academy'),
        'view_item' => __('View Course', 'academy'),
        'search_items' => __('Search Courses', 'academy'),
        'not_found' =>  __('No Courses Found', 'academy'),
        'not_found_in_trash' => __('No Courses Found in Trash', 'academy'),
     ),
    'public' => true,
    'exclude_from_search' => false,
    'capability_type' => 'post',
    'map_meta_cap' => true,
    'hierarchical' => false,
    'menu_position' => null,
    'supports' => array('title', 'editor', 'excerpt', 'thumbnail', 'author', 'revisions'),
    'rewrite' => array('slug' => __('course', 'academy')),
);

I am on thinking on smth like below. Just that doesn’t work because it needs to get linked somehow to products to get the price via meta_key course_product which contains the product id.

add_action('pre_get_posts' , 'changeCourseCountry');
function changeCourseCountry($query){
    $sortby = (isset($_GET['sortby']) && $_GET['sortby'] !== '') ? $_GET['sortby'] : '';
    if ($sortby !== '') {
        $sorting = explode('_', $sortby);
        $criteria = $sorting[0]; // title, date
        $order_sort = $sorting[1]; // ASC OR DESC
        if ($criteria !== 'price') {
            $query->set( 'orderby', array( $criteria => $order_sort ) );
        } else {
            // price query no
                if($criteria == 'price') {
                $meta_query = array(
                    array(
                        'meta_key' => '_price', // Not possbile directly
                        'type' => 'numeric',
                        'orderby' => 'meta_value meta_value_num',
                        'order' => 'ASC'
                    )
                );
                $query->set( 'meta_query', $meta_query );
            }
        }
    }
}

Read more here: Order custom post type linked to product by price


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: