Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I would like that each category link to the last post of each category.

  • category 1 ----> link to the last post of category 1
  • category 2 ----> link to the last post of category 2
  • category 3 ----> link to the last post of category 3

How can I do it?

share|improve this question
    
Where do you want to have this? In a hand-made category listing? In a category widget? For the URLs http://example.com/category/my-cat/ etc? This is not enough information. –  t f Apr 21 '13 at 19:50
    
There is really no such thing as the "first" post in a category. The display order depends on the query parameters. –  s_ha_dum Apr 21 '13 at 20:06
    
I want to have this in a menu. –  Mike Apr 28 '13 at 23:39

1 Answer 1

up vote 0 down vote accepted

You can filter category_link and replace the URL here. I have used the newest post in the following example, because first could also mean the oldest and that sounds … strange. :)

add_filter( 'category_link', 'wpse_96677_cat_link_to_first_post', 10, 2 );

function wpse_96677_cat_link_to_first_post( $url, $term_id )
{
    $term = get_term( $term_id, 'category' );

    // sub-terms only
    if ( ! isset ( $term->parent ) or 0 == $term->parent )
        return $url;

    $post = get_posts(
        array(
            'numberposts' => 1,
            'category'   => $term_id
        )
    );

    if ( ! $post )
        return $url;

    return get_permalink( $post[0]->ID );
}
share|improve this answer
    
Ok, thanks... And If I want to link to a post only the second level of categories? –  Mike Apr 21 '13 at 20:03
    
@Mike I made an update, the links are now changed for categories with parents only. –  toscho Apr 21 '13 at 20:08
    
Wow! Thank you very much :) –  Mike Apr 21 '13 at 20:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.