• I have a list of movies where the year and imdbTitle are stored in postmeta.

    I need to sort

    1. By year
    2. By imdbTitle and post_title by relavence to the search “the rundown”
    3. By post_content

    Here are my args for query_posts

    Array
    (
        [offset] => 0
        [meta_query] => Array
            (
            )
    
        [s] => the rundown
        [orderby] => meta_value_num
        [meta_key] => year
        [order] => asc
    )

    I hook into post_where and add

    $where .= " OR ({$wpdb->postmeta}.meta_key = 'imdbTitle' AND {$wpdb->postmeta}.meta_value LIKE '%".get_search_query()."%')";

    which allows the imdbTitle to be search for as well as the post_title

    I’ve then hooked into the posts_orderby and added the following sql

    (CASE
        WHEN
            wp_posts.post_title LIKE '%the rundown%' OR
            wp_postmeta.meta_value LIKE '%the rundown%' THEN 1
        WHEN
            (wp_posts.post_title LIKE '%the%' AND
            wp_posts.post_title LIKE '%rundown%' ) OR
            (wp_postmeta.meta_value LIKE '%the%' AND
            wp_postmeta.meta_value LIKE '%rundown%' ) THEN 2
        WHEN
            wp_posts.post_title LIKE '%the%' OR
            wp_postmeta.meta_value LIKE '%the%' OR
            wp_posts.post_title LIKE '%rundown%' OR
            wp_postmeta.meta_value LIKE '%rundown%' THEN 3
        WHEN
            wp_posts.post_content LIKE '%the rundown%' THEN 4
        ELSE 5
    END)

    This is added to the end of the order by which also has this at the start

    wp_postmeta.meta_value+0 ASC,

    I think the issue is wp_postmeta.meta_value+0 ASC because both the year and imdbTitle are postmeta.

    Is there a way to get around this? Or a better way to do this?

The topic ‘Complex Orderby’ is closed to new replies.