Search code examples
phpwordpresssql-order-byadvanced-custom-fields

Display posts in the order of their selection


I've offert the possibility to my client to choose one by one the related post for each post. I've set up a custom field with ACF and use this to display the choosen posts or random posts :

<?php  $terms = get_the_terms( $post->ID , 'custom-taxonomy1' );  if ( !empty( $terms ) ) :?>
        <?php
        $related_acf = get_field('related_group');
        $rel_posts = $related_acf["related posts"];

        $related_ids = array();
        foreach ( $rel_posts as $rel_post) {
            array_push($related_ids, $rel_post['post']);
        }

        global $post;
        $current_post_type = get_post_type( $post );
    
        $terms = get_the_terms( $post->ID , 'custom-taxonomy1' ); 
        $term_ids = array_values( wp_list_pluck( $terms,'term_id' ) );
        $post_count_skrn = get_theme_mod('progression_studios_media_more_like_post_count', '3');
        
        if ( count($related_ids) > 0 ) {
            $args=array(
                'post_type' => array('custompost1', 'custompost2', 'post'),
                'post__in' => $related_ids
            );
        } else {
            $args=array(
                'post_type' => $current_post_type,
                'posts_per_page'=> $post_count_skrn, 
                'orderby'=>'rand', // Randomize the posts
                'post__not_in' => array( $post->ID ),
                'tax_query' => array(
                    array(
                        'taxonomy'  => 'video-genres',
                        'terms'     => $term_ids,
                        'field' => 'id',
                        'operator'  => 'IN'
                    )
                ),  
            );
        }   

So I wonder if I can add something like :

if ( count($related_ids) > 0 ) {
            $args=array(
                'post_type' => array('custompost1', 'custompost2', 'post'),
                'orderby'=>'XXXXX', // Ordering the posts with the order of selection
                'post__in' => $related_ids
            );   

Best regards, Clément


Solution

  • Wordpress have 'orderby'=>'post__in'

    Posts will now be displayed according to their position in the $related_ids array

     $args=array(
     'post_type' => array('custompost1', 'custompost2', 'post'),
     'orderby'=>'post__in', // Ordering the posts with the order of selection
     'post__in' => $related_ids
      );