• Resolved andrejcremoznik

    (@andrejcremoznik)


    I have a WP_Query followed by a loop through the provided results. The SQL the query runs looks like this:

    SELECT SQL_CALC_FOUND_ROWS  xyz_posts.ID
    FROM xyz_posts
    INNER JOIN xyz_term_relationships ON (xyz_posts.ID = xyz_term_relationships.object_id)
    WHERE 1=1
    AND ( xyz_term_relationships.term_taxonomy_id IN (2) )
    AND xyz_posts.post_type = 'some_tax'
    AND (xyz_posts.post_status = 'publish')
    GROUP BY xyz_posts.ID
    ORDER BY xyz_posts.menu_order DESC
    LIMIT 6, 6

    This is insufficient in my case. I need to extend the ORDER BY clause like this:

    ORDER BY xyz_posts.menu_order DESC, xyz_posts.ID

    I don’t think there’s a way to add that to the SQL via WP_Query arguments.

    How do I go about solving this?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Use the ‘posts_orderby’ filter. Your callback is passed the current WP_Query orderby clause. Append your extension and return the altered clause.

    Unless some sort of conditional is used, this will be applied to all post queries. Your callback is passed the WP_Query object as a second parameter, from that you should be able to determine if extending the clause is appropriate or not.

    Thread Starter andrejcremoznik

    (@andrejcremoznik)

    Your callback is passed the WP_Query object as a second parameter

    I’m not getting the second parameter.

    function custom_orderby($orderby, $query = false) {
    	if($query !== false) die(var_dump($query));
    	return $orderby;
    }
    add_filter('posts_orderby', 'custom_orderby');

    I’m not getting any dies on templates with custom queries. Any idea?

    Thread Starter andrejcremoznik

    (@andrejcremoznik)

    Right, I forgot about the 4th add filter param.

    add_filter('posts_orderby', 'custom_orderby', 10, 2);

    Thread Starter andrejcremoznik

    (@andrejcremoznik)

    Resolved.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘WP_Query ordering insufficient, how to extend the SQL?’ is closed to new replies.