Advertisement
catchmahesh

sticky posts in category page

May 5th, 2017
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.14 KB | None | 0 0
  1. function get_term_sticky_posts()
  2. {
  3.     // First check if we are on a category page, if not, return false
  4.     if ( !is_category() )
  5.         return false;
  6.  
  7.     // Secondly, check if we have stickies, return false on failure
  8.     $stickies = get_option( 'sticky_posts' );
  9.  
  10.     if ( !$stickies )
  11.         return false;
  12.  
  13.     // OK, we have stickies and we are on a category page, continue to execute. Get current object (category) ID
  14.     $current_object = get_queried_object_id();
  15.  
  16.     // Create the query to get category specific stickies, just get post ID's though
  17.     $args = [
  18.         'nopaging' => true,
  19.         'post__in' => $stickies,
  20.         'cat' => $current_object,
  21.         'ignore_sticky_posts' => 1,
  22.         'fields' => 'ids',
  23.         'post_status' => 'publish'
  24.     ];
  25.     $q = get_posts( $args );
  26.  
  27.     return $q;
  28. }
  29.  
  30. add_action( 'pre_get_posts', function ( $q )
  31. {
  32.     if ( !is_admin() // IMPORTANT, make sure to target front end only
  33.          && $q->is_main_query() // IMPORTANT, make sure we only target the main query
  34.          && $q->is_category() // Only target category archives
  35.     ) {
  36.         // Check if our function to get term related stickies exists to avoid fatal errors
  37.         if ( function_exists( 'get_term_sticky_posts' ) ) {
  38.             // check if we have stickies
  39.             $stickies = get_term_sticky_posts();
  40.  
  41.             if ( $stickies ) {
  42.                 // Remove stickies from the main query to avoid duplicates
  43.                 $q->set( 'post__not_in', $stickies );
  44.  
  45.                 // Check that we add stickies on the first page only, remove this check if you need stickies on all paged pages
  46.                 if ( !$q->is_paged() ) {
  47.  
  48.                     // Add stickies via the the_posts filter
  49.                     add_filter( 'the_posts', function ( $posts ) use ( $stickies )
  50.                     {  
  51.                         $term_stickies = get_posts( ['post__in' => $stickies, 'nopaging' => true] );
  52.  
  53.                         $posts = array_merge( $term_stickies, $posts );
  54.  
  55.                         return $posts;
  56.                     }, 10, 1 );
  57.                 }
  58.             }
  59.         }
  60.     }
  61. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement