WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Custom query on archive page with custom meta_value_num

[Resolved] Custom query on archive page with custom meta_value_num

  • I trying to add parameters to an archive page.

    So I verified that the following method works:
    query_posts($query_string . '&order=ASC&meta_key=mykey&orderby=meta_value_num')
    My problem is thus:
    My meta-value as-is can’t be sorted properly; it first has to be alter via the php substr() function. But that breaks the query.

    Any ideas how to get this done?

    I’ve seen solutions posted where the database is queried directly, but aside from that obviously not being ideal, I also couldn’t figure out how to page that.

    Any help would be immensely appreciated 🙂

Viewing 5 replies - 1 through 5 (of 5 total)
  • You can use a filter to apply a MySQL substring function to the sort key. You did not specify the substring you need, so for this example I assume starting at position 3 for a length of 5. The example is UNTESTED, but should be close.

    function mam_posts_orderby ($orderby) {
       global $mam_global_orderby;
       if ($mam_global_orderby) $orderby = $mam_global_orderby;
       return $orderby;
    }
    add_filter('posts_orderby','mam_posts_orderby');
    $mam_global_orderby = '(substr(meta_value,3,5)+0) ASC';
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    query_posts($query_string . '&order=ASC&meta_key=mykey&orderby=meta_value_num' . "&paged=$paged");

    Here is a reference to the MySQL substring function: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substr

    “Nothing Found”

    I changed the substr() to start at 14 for 10 chars.

    No success 🙁

    To see if the proper query is produced, place this line just after the query_posts() line:

    global $wp_query; print_r("<p>REQUEST:$wp_query->request</p>");

    Post the output here.

    You were right the first time! Once I output the request (awesome feature to know, btw), I saw that the generic key “mykey” wasn’t what I actually needed!

    Thank you! /embarrassed

    Glad you got it fixed. Now, please use the dropdown on the right to mark this topic ‘Resolved’ so that others can see that there is a solution.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘[Resolved] Custom query on archive page with custom meta_value_num’ is closed to new replies.