Show only top 3 posts from 3 categories in order on home page

admin2025-01-07  5

This function will show the last 3 posts from any category on front page:

  // Only top 3 posts from CHR category
  add_action('pre_get_posts', 'ad_filter_categories');
  function ad_filter_categories($query) {
  if ($query->is_main_query() && is_home()) {
  $query->set('category_name','chatham-house-rules');
  $query->set('showposts', 3);
}

I want to do this twice more with two other categories but it will only ever work with one. It also defaults to the posts_per_page setting in the Admin panel. Any ideas how I can achieve 3 latest posts from 3 categories in specific order on front page?

This function will show the last 3 posts from any category on front page:

  // Only top 3 posts from CHR category
  add_action('pre_get_posts', 'ad_filter_categories');
  function ad_filter_categories($query) {
  if ($query->is_main_query() && is_home()) {
  $query->set('category_name','chatham-house-rules');
  $query->set('showposts', 3);
}

I want to do this twice more with two other categories but it will only ever work with one. It also defaults to the posts_per_page setting in the Admin panel. Any ideas how I can achieve 3 latest posts from 3 categories in specific order on front page?

Share Improve this question edited May 5, 2015 at 9:40 Pieter Goosen 55.4k23 gold badges115 silver badges209 bronze badges asked May 5, 2015 at 9:38 buksidabuksida 91 silver badge3 bronze badges 1
  • Yes - a page template for your home page will allow you to do this. You'll need multiple loops or another way to create your three separate category sections. codex.wordpress.org/Class_Reference/… – jdm2112 Commented May 5, 2015 at 15:49
Add a comment  | 

3 Answers 3

Reset to default 0

There are multiple ways to go about this, but one way I would consider if I were you would be to do it like this. On the index.php or whatever page the posts appear on do the following three times each with different categories:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$arguments = array(
    'category_name' => 'category'
    'posts_per_page' => 3,
    'paged' => $paged
);
$wp_query->query($arguments);
if (have_posts()) :
   while (have_posts()) : the_post();
       the_content();
    endwhile;
endif;

The category_name can be a comma delimited string that should allow you to have three or more categories.

The paged parameter is needed when setting the posts per page this way. If that isn't done, then the posts don't show up correctly on the subsequent post pages.

The WP_Query reference, shows all the filters that can used in the query. It also offers up an alternative way of using the query.

WP_Query allows you to define a whole lot of complex selection criteria to match individual posts to. However, what you want is effectively a criterium for the complete set that is returned from the query. This leaves you with two possible approaches:

  1. Use one query that returns a sufficient amount of posts, so you are sure at least one post from each category is present. Then loop through that set an pick the first post of each category.
  2. Use three queries that return one post from each category and merge the results.

Which one is best depends on the circumstances. The latter one is logically most sound, but queries the database thrice, so may be a drain on your resources.

define an array $categories where each key is a category slug and its corresponding value is the order in which you want to display the categories on the front page.

Replace category-2-slug and category-3-slug with the actual slugs of your categories.

add_action('pre_get_posts', 'ad_filter_categories');

function ad_filter_categories($query) {
    // Check if it's the main query and it's the home page
    if ($query->is_main_query() && is_home()) {
        // Set up an array of category slugs and their corresponding order
        $categories = array(
            'chatham-house-rules' => 1, // Category 1
            'category-2-slug' => 2, // Category 2
            'category-3-slug' => 3, // Category 3
        );

        // Sort categories by their order
        asort($categories);

        // Initialize an empty array to store category queries
        $category_queries = array();

        // Loop through the sorted categories
        foreach ($categories as $category_slug => $order) {
            // Set up query parameters for each category
            $category_query_args = array(
                'category_name' => $category_slug,
                'posts_per_page' => 3, // Limit to 3 posts per category
            );

            // Add the query parameters to the array
            $category_queries[] = $category_query_args;
        }

        // Merge the individual category queries using 'relation' => 'OR' to combine them
        $query->set('post_type', 'post');
        $query->set('posts_per_page', -1); // Set a high value to ensure all posts are retrieved
        $query->set('meta_key', 'date');
        $query->set('orderby', 'meta_value');
        $query->set('order', 'DESC');
        $query->set('meta_query', array(array('key' => '_thumbnail_id')));
        $query->set('tax_query', array(
            'relation' => 'OR',
            $category_queries
        ));
    }
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736263364a884.html

最新回复(0)