Support

Account

Home Forums General Issues Custom query ordered list by field

Solved

Custom query ordered list by field

  • I’ve tried to solve this problem by myself, but it seems that I have a lack of basic PHP-Wordpress knowledge. 🙂

    The situation is easy: I have a defined custom post type named scripts with different fields (ACF made), one of them is called “video_number”. There are several posts with a value e.g. 70 for this “video_number”. Understandably there are many other video numbers with each a few posts. What I want to achieve is a list, grouped by the video_number.

    The list should look like:

    video 70
    entry 4
    entry 5
    entry 6

    video 75
    entry 10
    entry 11
    entry 12

    … etc

    Now I don’t know how to realize this with PHP. I’ve studied the documentation of ACF, but all I achieved was a normal list of all entries.

    Actualy the code looks like:

    $the_query = new WP_Query(array(
    	'post_type'			=> 'scripts',
    	'posts_per_page'	=> -1,
    	'meta_key'			=> 'video_number',
    	'orderby'			=> 'meta_value_num',
    	'order'				=> 'ASC'
    ));
    
    ?>
    <?php if( $the_query->have_posts() ): ?>
    	<ul>
    	<?php while( $the_query->have_posts() ) : $the_query->the_post(); 
    
    		$class = get_field('video_number');
    
    		?>
    		<li class="<?php echo $class; ?>">
    			<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    		</li>
    	<?php endwhile; ?>
    	</ul>
    <?php endif; ?>
    
    <?php wp_reset_query();	 // Restore global post data stomped by the_post(). ?>

    I know I have to implement another loop or something, but I can’t get it to work.

    I appreciate any help. Thanks!

    Adriano

  • Hi @sonnenschauer

    I believe your code sorts the posts based on the video number, right?

    If you need to show the video number title so the result looks like grouped, then I think you can do it like this:

    <?php if( $the_query->have_posts() ): ?>
        <?php $current_group = ''; ?>
        <ul>
        <?php while( $the_query->have_posts() ) : $the_query->the_post(); 
    
            $class = get_field('video_number');
            
            if( $class != $current_group ) {
                echo '<h2>Video '. $class .'</h2>';
                $current_group = $class;
            }

    I hope this helps 🙂

  • Hi James

    Fantastic, thank you very much!
    That points me into the right direction and now I just have to combine this with the bootstrap accordion code and I will get a nice dropdown list.

    Greetings,
    Adriano

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

You must be logged in to reply to this topic.