Support

Account

Home Forums General Issues Query / order by custom field twice

Solving

Query / order by custom field twice

  • Hello I’ve a custom post type “events” with the custom fields “artists” and “date” .
    I want to get a ordered list of artists (by menu id) and below each artist an ordered list of his dates (DESC). Could anybody give me a hint?

    Best
    P.

  • Ive manged to do it like this:

    <?php // WP_Query arguments
            $args = array(
            	'post_type'              => array( 'artists' ),
               'orderby' => 'menu_order',
    
            );
    
            // The Query
            $query = new WP_Query( $args );
    
            // The Loop
            if ( $query->have_posts() ) {
            	while ( $query->have_posts() ) {
            		$query->the_post();
    
                $id = get_the_id();
                $title = get_the_title();
    
                    $args_inner = array(
                    	'post_type'              => array( 'events' ),
                      'meta_key'		=> 'event_artist',
                    	'meta_value'	=> $id,
                      'orderby'			=> 'event_date',
    	                'order'				=> 'ASC'
    
                    );
    
                    // The Query
                    $query_inner = new WP_Query( $args_inner );
    
                    // The Loop
                    if ( $query_inner->have_posts() ) {
    
                      echo '<h2>'.$title.'</h2>';
    
                    	while ( $query_inner->have_posts() ) {
                    		$query_inner->the_post();
    
                        $date = get_field('event_date');
                        $artist_obj = get_field('event_artist');
                        $event_title = get_the_title();
    
                        echo '<li>';
                        echo $date;
                        echo $artist_obj -> post_title;
                        echo $event_title;
                        echo '</li>';
    
                    	}
                    } else {
                    	// no posts found
                    }
    
                    // Restore original Post Data
                    wp_reset_postdata();
    
            	}
            } else {
            	// no posts found
            }
    
            // Restore original Post Data
            wp_reset_postdata();
    
          ?>

    Is ther a possiblity to add a parameter to show only future events from today onwards?

  • Unfortunately the sorting doesn’t work as expected – seems that the “orderby” in the second query is ignored….

    Could someone tell me what I’m doing wrong, please…

    Best
    P.

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

The topic ‘Query / order by custom field twice’ is closed to new replies.