Documentation - How To - Programmatically retrieve the sort_id and sort_view_id by specified arguments

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPrint this page

Programmatically retrieve the sort_id and sort_view_id by specified arguments

Within the Dashboard multiple sorts can be created to match different area of your side. This is a powerful tool to make sorting virtually possible for every little area of a website.

There are situations when at the code level the sort_id or sort_view_id is required to know before make further processing. This is an easy to achieve, mainly relying on query_match_sort_id() method included within functions class. This function is available globally, by invoking the $APTO superglobal variable.

The following example retrieve the sort_id and sort_view_id for area consisting of post_type => ‘product’, taxonomy => product_cat and a term_id => 26. Particularly this correspond to a WooCommerce area, a Product Category Term page.

    global $APTO;
    $sortID =   FALSE;
    $args   =   array(
                        '_adminsort' =>  array('yes')  
    //create the arguments of a query
    $query  =   new stdClass();
    //set the post type
    $query->query_vars['post_type'] =   'product';
    //set taxonomy
    $query->tax_query->queries['relation']  =   'AND';
    $query->tax_query->queries[]    =   array(
                                                'taxonomy'  =>   'product_cat',
                                                'field'     =>   'term_id',
                                                'terms'     =>   array('26'),
                                                'operator'  =>  'IN'
    $sort_view_id   =   $APTO->functions->query_match_sort_id($query, $args);
    if($sort_view_id    >   0)
            $sort_view_post     =   get_post($sort_view_id);
            $sortID             =   $sort_view_post->post_parent;

A fully qualified $query object class can be passed through instead, either by using existing if apply, or create a new one, for example:

     $args = array(
                'post_type'                 => 'product',
                'ignore_custom_sort'        => TRUE,
                'suppress_filters'          => TRUE,
                'tax_query'                 => array(
                                                    'taxonomy'      => 'product_cat',
                                                    'field'         => 'term_id',
                                                    'terms'         => 10

    $query = new WP_Query($args);

The ‘ignore_custom_sort’ and ‘suppress_filters’ should be used but not mandatory to make the query rendering as fast as possible as we are not interested in actual results but the class object. More details upon constructing a full custom query at Class Reference/WP Query