Sort post data on the basis of custom meta acf fields

In this article, I sorted the posts data on the basis of categories like if you selected a business category and you want to display posts according to our defined positions then follow these steps.

  1. Create ACF fields; one for category taxonomy field and second for the position of the post. This is an edit post page screenshot.

2. Add this code into the archive template

<?php
        $cat_id = get_queried_object_id();
        $pos_key = ”;
        while ( have_posts() ) : the_post();
            $cat_1 = get_field(‘category_1’);
            $cat_2 = get_field(‘category_2’);
            $cat_3 = get_field(‘category_3’);
            $cat_4 = get_field(‘category_4’);
            $cat_5 = get_field(‘category_5’);
            if( $cat_1 && $cat_1 == $cat_id ) {
                $pos_key = ‘position_1’;
            }
            else if ( $cat_2 && $cat_2 == $cat_id ) {
                $pos_key = ‘position_2’;
            }
            else if ( $cat_3 && $cat_3 == $cat_id ) {
                $pos_key = ‘position_3’;
            }
            else if ( $cat_4 && $cat_4 == $cat_id ) {
                $pos_key = ‘position_4’;
            }
            else if ( $cat_5 && $cat_5 == $cat_id ) {
                $pos_key = ‘position_5’;
            }
            $posts = get_posts(array(
                ‘posts_per_page’    => -1,
                ‘meta_key’          => $pos_key,
                ‘orderby’           => ‘meta_value’,
                ‘order’             => ‘DESC’
            ));
            foreach($posts as $post) {
                echo $post->post_title . “<br/>”;
            }
            break;
        endwhile;
    ?>