Home › Forums › General Issues › 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
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
The topic ‘Custom query ordered list by field’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.