Support

Account

Home Forums General Issues Filter query by custom field and sort orderby another custom field

Solved

Filter query by custom field and sort orderby another custom field

  • Hello,
    Im trying to make a query in which i want to order the results by a custom field and also filter them by another.
    I know how to do it separately but i dont know how to combine these 2 together.
    Here is my code to orderby only

    $args=array(
      'post_type' => $type,
      'post_status' => 'publish',
      'meta_key'		=> 'start_time',
      'orderby'		=> 'meta_value_num',
       'order'			=> 'ASC',
      'posts_per_page' => -1
      );
    

    i want also to filter these results if the “banner” custom field value is 1.

    thank you

  • This should do the trick:

    <?php
    
    $args = array(
      'post_type'      => $type,
      'post_status'    => 'publish',
      'posts_per_page' => -1,
      'meta_query'     => array(
        array(
          'key'        => 'banner',
          'compare'    => '=',
          'value'      => 1
        )
      ),
      'meta_key'       => 'start_time'
      'orderby'        => 'meta_value_num',
      'order'          => 'ASC'
    );
    
    ?>

    See the documentation here: http://www.advancedcustomfields.com/resources/how-to-query-posts-filtered-by-custom-field-values/

  • Any idea why this would not be working for me? I’m going round in circles trying to figure it out, please could you tell me where I’m going wrong.

    $news_archive = ( int )( get_query_var('news_archive')  === 'true' );
    
    $news_query = new WP_Query( array(
        'post_type' => 'news',
        'post_status' => 'publish',
        'posts_per_page' => $news_archive ? 12 : 5,
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key' => 'archive',
                'value' => $news_archive,
                'compare' => '=',
            ),
            array(
                'key' => 'featured_article',
                'value' => 0,
            )
        ),
        'meta_key' => 'date', 
        'orderby' => 'meta_value_num',
        'order' => 'ASC'
    ));

    No change in the order of my posts.

    To begin with I thought that there might be restrictions on using the name date for my custom field.. but that doesn’t seem to be the case because I tested by adding a test_date field and trying it with that.

    I’ve also tried changing the output format of the date picker field, but that also doesn’t seem to affect anything because in newer versions of ACF date field values are stored as YYYYMMDD in the database regardless.

    Please help.

  • @juliusbangert So your posts are still being shown in reverse chronological order even though you’re sorting them by date ascending? Have you tried print_r()-ing your $news_query results?

  • Thanks for your response @matthewmcvickar.
    My date field is a custom field created in ACF, not the post’s publish date.

    So I tried a print_r() of the $news_query but I’m really not sure what I’m looking for. ( nor is my knowledge of mysql all that good ).
    I’m pasting the output here in the hope that you might spot the problem.

    WP_Query Object
    (
        [query] => Array
            (
                [post_type] => news
                [post_status] => publish
                [posts_per_page] => 12
                [meta_query] => Array
                    (
                        [relation] => AND
                        [0] => Array
                            (
                                [key] => archive
                                [value] => 1
                            )
    
                        [1] => Array
                            (
                                [key] => featured_article
                                [value] => 0
                            )
    
                    )
    
                [meta_key] => date
                [orderby] => meta_value_num
                [order] => DESC
            )
    
        [query_vars] => Array
            (
                [post_type] => news
                [post_status] => publish
                [posts_per_page] => 12
                [meta_query] => Array
                    (
                        [relation] => AND
                        [0] => Array
                            (
                                [key] => archive
                                [value] => 1
                            )
    
                        [1] => Array
                            (
                                [key] => featured_article
                                [value] => 0
                            )
    
                    )
    
                [meta_key] => date
                [orderby] => meta_value_num
                [order] => DESC
                [error] => 
                [m] => 
                [p] => 0
                [post_parent] => 
                [subpost] => 
                [subpost_id] => 
                [attachment] => 
                [attachment_id] => 0
                [name] => 
                [static] => 
                [pagename] => 
                [page_id] => 0
                [second] => 
                [minute] => 
                [hour] => 
                [day] => 0
                [monthnum] => 0
                [year] => 0
                [w] => 0
                [category_name] => 
                [tag] => 
                [cat] => 
                [tag_id] => 
                [author] => 
                [author_name] => 
                [feed] => 
                [tb] => 
                [paged] => 0
                [meta_value] => 
                [preview] => 
                [s] => 
                [sentence] => 
                [title] => 
                [fields] => 
                [menu_order] => 
                [embed] => 
                [ignore_sticky_posts] => 
                [suppress_filters] => 
                [cache_results] => 1
                [update_post_term_cache] => 1
                [lazy_load_term_meta] => 1
                [update_post_meta_cache] => 1
                [nopaging] => 
                [comments_per_page] => 50
                [no_found_rows] => 
            )
        [meta_query] => WP_Meta_Query Object
            (
                [queries] => Array
                    (
                        [0] => Array
                            (
                                [key] => date
                            )
    
                        [1] => Array
                            (
                                [0] => Array
                                    (
                                        [key] => archive
                                        [value] => 1
                                    )
    
                                [1] => Array
                                    (
                                        [key] => featured_article
                                        [value] => 0
                                    )
    
                                [relation] => AND
                            )
    
                        [relation] => AND
                    )
    
                [relation] => AND
                [meta_table] => wp_postmeta
                [meta_id_column] => post_id
                [primary_table] => wp_posts
                [primary_id_column] => ID
                [table_aliases:protected] => Array
                    (
                        [0] => wp_postmeta
                        [1] => mt1
                        [2] => mt2
                    )
    
                [clauses:protected] => Array
                    (
                        [wp_postmeta] => Array
                            (
                                [key] => date
                                [compare] => =
                                [alias] => wp_postmeta
                                [cast] => CHAR
                            )
    
                        [mt1] => Array
                            (
                                [key] => archive
                                [value] => 1
                                [compare] => =
                                [alias] => mt1
                                [cast] => CHAR
                            )
    
                        [mt2] => Array
                            (
                                [key] => featured_article
                                [value] => 0
                                [compare] => =
                                [alias] => mt2
                                [cast] => CHAR
                            )
    
                    )
    
                [has_or_relation:protected] => 
            )
    
        [date_query] => 
        [request] => SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts  INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )  INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id )  INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) WHERE 1=1  AND ( 
      wp_postmeta.meta_key = 'date' 
      AND 
      ( 
        ( mt1.meta_key = 'archive' AND mt1.meta_value = '1' ) 
        AND 
        ( mt2.meta_key = 'featured_article' AND mt2.meta_value = '0' )
      )
    ) AND wp_posts.post_type = 'news' AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order, wp_postmeta.meta_value+0 DESC LIMIT 0, 12
        [posts] => Array
            (
            ........
            )
    )
    

    I’ve edited some of the empty entries out of it because it was even longer.

  • Here, you can see from this screenshot that the output order from the WP_Query is totally unrelated to my date custom field (which is display as a date under each article).

  • It looks like your posts are still being sorted DESC, and that the menu_order is also being sorted on first. Do you have any plugins running that might affect this query? Could you try using get_posts() instead of new WP_Query()?

  • AH HA! Yes, totally didn’t think about that.
    I have a plugin called Post Types Order running, it let’s the client drag and drop posts in the edit screen list to re-order. I just tested disabling it and that worked!

    However, I need this plugin running for the other post-types, any idea how to over-rule it for this instance?

  • @juliusbangert Looks like you can ignore it with some arguments provided by that plugin: https://www.nsp-code.com/advanced-post-types-order-api/sample-usage. Give that a shot?

  • Thank you very much @matthewmcvickar, you were totally on it there! Turns out there’s two ways to do it.. the first is to turn off the auto-sort functionality in the plugin’s settings or you can use the ignore_custom_sort parameter in the query.

    'ignore_custom_sort' => true,
    'meta_key' => 'date', 
    'orderby' => 'meta_value_num',
    'order' => 'DESC'

    Thank you for your help.

  • Happy to help, glad you were able to get it working! Have a good one. 🙂

  • Thank you @juliusbangert , This is working fine.

Viewing 12 posts - 1 through 12 (of 12 total)

The topic ‘Filter query by custom field and sort orderby another custom field’ is closed to new replies.