The Support Forums will be in read-only mode for a scheduled maintenance window on 01 September 2016 14:00 UTC - 20:00 UTC. More information.

[resolved] Custom query on archive page with custom meta_value_num (6 posts)

  1. mendelk
    Posted 4 years ago #

    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 :)

  2. vtxyzzy
    Posted 4 years ago #

    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;
    $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

  3. mendelk
    Posted 4 years ago #

    "Nothing Found"

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

    No success :(

  4. vtxyzzy
    Posted 4 years ago #

    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.

  5. mendelk
    Posted 4 years ago #

    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

  6. vtxyzzy
    Posted 4 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic