admin管理员组

文章数量:1129001

I want to display featured posts first, then all other posts not marked as featured on a category archive page. I am using a plugin that has functionality to mark posts as featured. I have figured out how to pull in those posts, but I'm unsure how to also include posts not marked as featured.

I tried creating two separate queries and then merging them together, but it's not putting the featured posts at the top. It also has to work for pagination and only show the featured posts on the first page, not the second, third, etc.

function get_cat_posts( $query ) {
  if ( $query->is_category() ) {
    $current_category = get_queried_object_id();
    $category_slug = get_term_by( 'id', $current_category, 'category' )->slug;
    $featured = get_option('featured_' . $category_slug );

    $featured_query = array(
      'post__in' => $featured
    );
    $featured_query = new WP_Query($featured_query);
    
    $regular_query = get_posts(array(
      'post__not_in' => $featured
    ));
    $regular_query = new WP_Query($regular_query);
    
    $query->posts = array_merge($featured_query->posts, $regular_query->posts);
  }
}

add_filter( 'pre_get_posts', 'get_cat_posts' );

本文标签: