0

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?

3
  • 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.
    – tfrommen
    Apr 21, 2013 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, 2013 at 20:06
  • I want to have this in a menu.
    – Mike
    Apr 28, 2013 at 23:39

1 Answer 1

1

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 );
}
2
  • Ok, thanks... And If I want to link to a post only the second level of categories?
    – Mike
    Apr 21, 2013 at 20:03
  • @Mike I made an update, the links are now changed for categories with parents only.
    – fuxia
    Apr 21, 2013 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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