Wordpress wp_query group by custom field

前端 未结 2 1090
星月不相逢
星月不相逢 2021-01-07 06:06

I have to make a search form where i have to populate a select by the states of custom posts types. Some of them have the same state, then I would like to group-by to have a

相关标签:
2条回答
  • 2021-01-07 06:27

    I had to make a few improvements to Chirag Patels Code, to get it working:

    <?php
        function  query_group_by_filter($groupby){
           global $wpdb;
    
           return $wpdb->postmeta . '.meta_value ';
        }
    ?>
    <?php add_filter('posts_groupby', 'query_group_by_filter'); ?>
    <?php $states = new WP_Query(array(
        'post_type' => 'observatoire',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'meta_key' => 'state'
    )); 
    ?>
    <?php remove_filter('posts_groupby', 'query_group_by_filter'); ?>
    <select id="" class="" name="siege_pays" >
         <option value=""></option>
    <?php
    while ( $states->have_posts() ) : $states->the_post();
    echo "<option value=".reset(get_post_custom_values('state')).">".reset(get_post_custom_values('state'))."</option>"; 
    endwhile;
    ?>
    </select>
    
    0 讨论(0)
  • 2021-01-07 06:30

    You can try below code:

    <?php
        function  query_group_by_filter($groupby){
           global $wpdb;
    
           return $wpdb->postmeta . '.meta_key = "state"';
        }
    ?>
    <?php add_filter('posts_groupby', 'query_group_by_filter'); ?>
    <?php $states = new WP_Query(array(
        'post_type' => 'observatoire',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'meta_key' => 'state'
    )); 
    ?>
    <?php remove_filter('posts_groupby', 'query_group_by_filter'); ?>
    <select id="" class="" name="siege_pays" >
         <option value=""></option>
    <?php
    while ( $states->have_posts() ) : $states->the_post();
    echo "<option value=".get_field_object('state').">".get_field_object('state')."</option>"; 
    endwhile;
    ?>
    </select>
    

    Query Look like:

    SELECT wp_posts.*
    FROM wp_posts INNER JOIN wp_postmeta 
      ON (wp_posts.ID = wp_postmeta.post_id)
    WHERE wp_posts.post_type = 'observatoire'
      AND (wp_posts.post_status = 'publish')
      AND (wp_postmeta.meta_key = 'state' )
    GROUP BY wp_postmeta.meta_key = "state"
    ORDER BY wp_posts.post_date DESC
    
    0 讨论(0)
提交回复
热议问题