Sort by custom field value

I have a page where I only want to show posts from a specific category. At the same time, I want the posts to be sorted by a custom field value in my posts:

query_posts('category_name=' . str_replace(" ", "", $store_name) . '&meta_key=wpfp_favorites&orderby=meta_value_num');

The sorting is not working however. The posts are not sorted by the custom field value. Any ideas why? What do I need to make it work?

Read More

Added:
In a similar case, it is working perfectly:

query_posts('tag=' . $pagetitle . '&meta_key=wpfp_favorites&orderby=meta_value_num');

Related posts

Leave a Reply

2 comments

  1. Have you tried hard-coding the category parameter for testing, and additionally trying different methods to set the query parameters..

    Eg.

    query_posts( array( 'category_name' => 'myname', 'meta_ke' => 'wpfp_favorites', 'orderby' => 'meta_value_num' ) );
    query_posts( array( 'cat' => N, 'meta_key' => 'wpfp_favorites', 'orderby' => 'meta_value_num' ) );
    query_posts( array( 'cat__in' => array( N ), 'meta_key' => 'wpfp_favorites', 'orderby' => 'meta_value_num' ) );
    

    Where N would be a numerical ID number for the category.

    Logically the query class should accept both a category and a meta key, whilst being able to order by meta key, i can’t see any conditional logic that would prevent these two parameters working alongside one another..

    Maybe an additional test would be to set the meta_value parameter to and see if this has an effect, you could use something like this to avoid the need to match a particular value.. (which would match any post with that custom field key where the value isn’t an empty string)

    query_posts( array( 
        'cat' => N, 
        'meta_key' => 'wpfp_favorites', 
        'meta_value' => '', 
        'meta_compare' => '!=', 
        'orderby' => 'meta_value_num' 
    ) );
    

    RE: Get category ID…. get_cat_ID(‘nameofcat’) or alternatively take a peek at the edit URL for the category in the administration area it should contain the category ID..

    🙂

  2. Dump generated SQL request. See if everything looks fine, try to run it directly on database.

    add_filter( 'posts_request', 'dump_request' );
    
    function dump_request( $input ) {
    
        var_dump($input);
    
        return $input;
    }