Loop for the Latest post from each term in a custom taxonomy for a given custom post type

Hi,

I’m trying to pull the latest post from each term in a custom taxonomy for a specific post type.

The post type is: my_mags

The Taxonomy is: my_mags_areas

I have managed to get this code together that works and displays the name for each term but shows only the latest post in my_mags repeated under each term name.

<?php

wp_reset_query();

$args1 = array(

‘taxonomy’ => ‘my_mags_areas’,

);

$cats = get_categories( $args1 );

foreach ($cats as $cat) :

$args = array(

‘posts_per_page’ => 1,

‘post_type’ => ‘my_mags’,

‘cat’ => $cat->name,

);

query_posts($args);

if (have_posts()) :

echo ‘<h2>Latest Posts in ‘.$cat->name.’ Category</h2>’;

while (have_posts()) : the_post(); ?>

<?php the_title(); ?>

<?php endwhile; ?>

<?php else :

echo ‘<h2>No Posts for ‘.$cat->name.’ Category</h2>’;

endif; wp_reset_query; ?>

<?php endforeach; ?>

Any help would be greatly appreciated.

Thankyou

  • David
    • Flash Drive

    Hi Jack,

    Thanks for your reply.

    Yes that is almost right.

    At the moment i have 7 categories(/terms?) in my custom taxonomy and in each of the 7 i have 1 post. Also posts will only ever have one cat assigned.

    It loops through each categories(/terms?) in my_mags_areas displaying the name, then it should show the latest post from each under the term title. The problem is it seems to shows the same post under each. The post that is replicated under each is the latest post created in my_mags. Even though that post isn’t in the given categories.

    Example output:

    LATEST POSTS IN AREA 1 CATEGORY

    – Post #7 Name

    LATEST POSTS IN AREA 2 CATEGORY

    – Post #7 Name

    LATEST POSTS IN AREA 3 CATEGORY

    – Post #7 Name

    LATEST POSTS IN AREA 4 CATEGORY

    – Post #7 Name

    LATEST POSTS IN AREA 5 CATEGORY

    – Post #7 Name

    LATEST POSTS IN AREA 6 CATEGORY

    – Post #7 Name

    LATEST POSTS IN AREA 7 CATEGORY

    – Post #7 Name

    Hope this helps.

    Thankyou

  • Jack Kitterhing
    • Code Norris

    Hi there @david

    I hope you are well today, first of all I’d like to apologize about the extreme delay with my reply on this. I missed your previous reply’s.

    This is quite strange, that it’s looping the same post through all custom output, do you have a link to where I can see this live please?

    Thank you, again sorry for the extreme delay.

    Kind Regards

    Jack.

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.