• nspace1999

    (@nspace1999)


    Hello everyone

    I read forums for 2 days and I can’t find the answers to what I want to do.

    I want to create a custom query to fetch all custom post type with a group by clause on 2 custom fields.
    The difficulty comes from the group by clause.
    Just looking for syntax

    Any ideas ?

Viewing 2 replies - 1 through 2 (of 2 total)
  • @nspace1999, You can use function something like below to fetch all custom post types title

    <?php
    $args = array(
        'post_type' => 'custom_post_type',
    );
    $loop = new WP_Query($args);
    
    while($loop->have_posts()): $loop->the_post();
        the_title();
    endwhile;
    wp_reset_query();
    ?>

    …and add a filter something like to append a GROUP BY clause to the current WP_Query

    function custom_posts_groupby( $groupby, $query )
    {
        global $wpdb;
        $groupby = "{$wpdb->posts}.ID";
    
        return $groupby;
    }
    add_filter( 'posts_groupby', 'custom_posts_groupby', 10, 2 );

    I hope this helps.

    Thread Starter nspace1999

    (@nspace1999)

    Hello… than you for answering. Actually I need somethiing more complex.

    I made a custom query and it worked for me :

    SELECT   mt1.*, mt2.*, GROUP_CONCAT(DISTINCT CONCAT(mt2.meta_value, '' , mt3.meta_value))  FROM wpjght_posts  INNER JOIN wpjght_postmeta ON (wpjght_posts.ID = wpjght_postmeta.post_id)
    INNER JOIN wpjght_postmeta AS mt1 ON (wpjght_posts.ID = mt1.post_id)
    INNER JOIN wpjght_postmeta AS mt2 ON (wpjght_posts.ID = mt2.post_id)
    INNER JOIN wpjght_postmeta AS mt3 ON (wpjght_posts.ID = mt3.post_id) WHERE 1=1  AND wpjght_posts.post_type = 'kine' AND (wpjght_posts.post_status = 'publish' OR wpjght_posts.post_status = 'future' OR wpjght_posts.post_status = 'draft' OR wpjght_posts.post_status = 'pending') AND (wpjght_postmeta.meta_key = 'wpcf-lat'
    AND mt1.meta_key = 'wpcf-lng'
    AND mt2.meta_key = 'wpcf-nom'
    AND mt3.meta_key = 'wpcf-prenom' ) GROUP BY mt1.meta_value, wpjght_postmeta.meta_value ORDER BY wpjght_posts.post_date DESC

    After 2 days working on it, hope it could help someone.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘wp_query with a group by clause’ is closed to new replies.