Count the number of relation posts in ACF
You can use this code to create an array of all the songs:
<?php
$args = array(
'post_type' => 'gig'
);
$countArray = []; //create an array where you can put all the song id's and the number of times played
?>
<?php $loop = new WP_Query($args); ?>
<?php if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
$posts = get_field('songs');
if( $posts ):
foreach( $posts as $post):
setup_postdata($post);
//if the song id already exists -> count + 1
if (array_key_exists($post->ID, $countArray)){
$countArray[$post->ID]++;
}
else { // otherwise the song is played 1 time
$countArray[$post->ID] = 1;
}
endforeach;
wp_reset_postdata();
endif;
?>
<?php endwhile; ?>
The code above will create an array of post ID's of songs and the number of times it is used in the post_type "gig".
Now you can use the array $countArray
and do whatever you want with it.
In your example you want to sort it, so you have to do arsort($countArray);
This way the array is sorted by it's value (the number of times played) from high to low.
Then you have to loop through the array: foreach ($countArray as $key => $value) { ?>
<?php echo get_post_permalink($key); //=the permalink of the song ?>
<?php echo get_the_title($key); //= the title of the song ?>
<?php echo $value; //number of times play in a gig ?>
<?php
}
So the full code is:
<?php
$args = array(
'post_type' => 'gig'
);
$countArray = [];
?>
<?php $loop = new WP_Query($args); ?>
<?php if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
$posts = get_field('songs');
if( $posts ):
foreach( $posts as $post):
setup_postdata($post);
if (array_key_exists($post->ID, $countArray)){
$countArray[$post->ID]++;
}
else {
$countArray[$post->ID] = 1;
}
endforeach;
wp_reset_postdata();
endif;
?>
<?php endwhile; ?>
<?php
arsort($countArray);
foreach ($countArray as $key => $value) {
?>
<?php echo get_post_permalink($key); //=the permalink of the song ?>
<?php echo get_the_title($key); //= the title of the song ?>
<?php echo $value; //number of times play in a gig ?>
<?php
}
?>
<?php else: ?>
<!-- No gigs available -->
<?php endif; ?>
<?php wp_reset_postdata(); ?>
You Could do like this in simple and short way:
$args = array(
'post_type' => 'gig'
);
$gigs = get_posts($args);
$songsarr = array();
foreach($gigs as $gig) {
$posts = get_field('songs', $gig->ID);
array_push($songsarr,$posts[0]);
}
//echo "<pre>;
//print_r($songsarr);
$countsongs = array_count_values($songsarr);
echo 'No. of Duplicate Items: '.count($countsongs).'<br><br>';
// print_r($countsongs);
foreach($countsongs as $songID => $songname){
echo get_the_title( $songID );
echo $songname;
}
I have Tried by making Two Custom Post Type(gig, songs) and I got count numbers of song this way that you can show in home page and also you can give condition in last foreach loop if song more than one etc..
Hope this will help you!