• I have several posts with a custom field named “series”. I want to group all posts by this custom field and below of this i want to list all posts which have not this custom field.

    First i wanted to get grouped custom field value and then to be able to query again for all posts with this custom value key and value. But even trying to get the unique custom values does not work.

    What i tried is this:

    <?php
        function  query_group_by_filter($groupby){
           global $wpdb;
    
           return $wpdb->postmeta . '.meta_key = "series"';
        }
    ?>
    
    <?php add_filter('posts_groupby', 'query_group_by_filter'); ?>
    
    <?php $states = new WP_Query(array(
        'meta_key' => 'series',
        'ignore_sticky_posts' => 1
    )); 
    ?>
    
    <?php remove_filter('posts_groupby', 'query_group_by_filter'); ?>
    
    <ul>
    <?php
    while ( $states->have_posts() ) : $states->the_post();
    
    $mykey_values = get_post_custom_values( 'series' );
    
    foreach ( $mykey_values as $key => $value ) {
        echo "<li>$key => $value ( 'series' )</li>"; 
    }   
    
    endwhile;
    ?>
    </ul>

    Whats wrong with this code?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    You will want to manipulate the ORDER BY clause, not GROUP BY. So use the “posts_orderby” filter and return something like wp_postmeta.meta_key ASC, wp_postmeta.meta_value ASC, wp_posts.post_date DESC.

    I’m not sure this is exactly what you need, the point is to specify the ordering, not grouping. Using the $wpdb table names is far superior to hard coding table names. I’m illustrating a possible value to return, not how you determine the value.

    The grouping clause doesn’t do what you think it does, if I’m able to correctly discern your thinking. It doesn’t literally group the results, its purpose is to break up the results into groups on which to perform aggregating SQL functions like SUM(), COUNT(), etc. It doesn’t affect the order in which the posts are listed. If you wanted a count of posts with the “series” meta key out of the results of a larger query, GROUP BY is the way to go. “Group” is unfortunately an ambiguous term, so its purpose is commonly misinterpreted.

    Thread Starter Yavuz Bogazci

    (@bogazci)

    Thank you! I will try it tomorrow evening and give you feedback. But when i understand you correctly, i need to sort by metada key and value and then in my foreach test if there is a new meta value to maybe set a new header etc.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Group by a custom value field wordpress posts’ is closed to new replies.