WordPress: retrieve first five items from all populated categories

I am trying to find a way to achive the following: I’d like to make a custom template. Within this template I’d like to list the name of each category on my site that has at least 1 item assigned to it. Beneath the category name (and link) I’d like to insert some content from the first x number of items that have that particular category assigned.

Just in case it makes a massive difference the items in question are not posts, but custom items.

Read More

Can anyone give me some pointers or help? I assume there will be something I can do with the wp_query function, but I’m not really sure how to inject it between each of the category titles, or indeed how to make it work with a category for which I can’t explicitly provide an id in the code).

Thank you.

Related posts

Leave a Reply

4 comments

  1. get_posts() is your ideal solution. For example:

    <?php $posts_array = get_posts( $args ); ?>
    
    <?php $args = array(
    'posts_per_page'   => 1,
    'category'         => $post_cat,
    'orderby'          => 'post_date',
    'order'            => 'DESC',
    'post_type'        => 'yourcustompostname',
    'post_status'      => 'publish',
    'suppress_filters' => true ); 
    
    
    $myposts = get_posts( $args );
    
    ///respective loop here ie : foreach $myposts as $mypost ... etc
    
    ?>
    

    Where $post_cat is the id of your category and post_type is the custom post type.

    To keep these ‘items’ organized I would create a custom post and then assign a category to those posts, for each respective category (if there are multiple). If there is just one, than you could live with just using a single category.

    EDIT:

    to get the categories assigned to this custom post take a look at this link

    Using the results from this you could assign the cat id’s to the variable created earlier: $post_cat.

  2. You have to use query_posts function

    query_posts(array('category_name'=>'category-slug','posts_per_page'=>'5'));

    then you need to do

    while ( have_posts() ) : the_post();

    and you can get the post id using:

    $p_id = get_the_ID();

    for more information : query_posts

  3. Here is the answer of your problem. You need to change the category id of own post category id .
    Here is the code. just copy and past it.

    $query1 = new WP_Query( array( 'post_type' => 'post','cat' =>'10,9') );
    

    Use the above query in loop and after loop,reset your query . see the below code.

    wp_reset_query();
    

    Please use it and let me know if needs anything else.