Akash Gajbhiye Akash Gajbhiye - 4 months ago 10
PHP Question

is there a way to display posts based on priority in the loop in wordpress?

I want to display post based on priorities and once they are displayed the priority should be lowered so that when next time page is reloaded or refreshed other posts are on the top and those that were already displayed should be at the bottom.

Answer

created a meta field 'priority_priority'

 <div id="games-container" class="col-md-12">
    <?php 
      $counter = 0;
      $args = array( 'post_type' => 'games', 'posts_per_page' => 10,
             'orderby'    => 'meta_value_num',
             'order'      => 'DES',
             'meta_query' => array(
                         array(
                                'key'     => 'priority_priority'
                            ),
                    ), );
      $loop = new WP_Query( $args );
     while ( $loop->have_posts() ) : $loop->the_post();
     if($counter < 2){           
       ?>
       <a href=<?php echo get_post_permalink()?>>
        <div id="mypost" class="col-md-5" style="min-height:400px;">
        <?php the_post_thumbnail('large');
         ?>
        </div>
        </a>
        <div class="col-md-1"></div>
    <?php
    $counter++;
     } 
    else {?>
    <a href=<?php echo get_post_permalink()?>>
     <div id="mypost" class="col-md-3">
         <!-- post display -->
         <?php the_post_thumbnail('medium'); ?>
        </div>
    </a>
        <div class="col-md-1"></div>
       <?php 
       }
     endwhile; 
     wp_reset_postdata();
     ?>
     </div>

then used the following code in post template page

<?php

     $post_id = get_the_ID();
       $priority = get_post_meta($post_id,'priority_priority',true); 
       if($priority>1)
       {     
          if(!isset($_COOKIE['visitor'.$post_id]))
          {        
               $bool=setcookie('visitor'.$post_id,$post_id,DAY_IN_SECONDS,'/');
               if(count($_COOKIE) > 0)
               {
                    $priority = $priority-1;
                    update_post_meta($post_id,'priority_priority',$priority);
               }
          }

       }
   get_header();
?>