0

I'm looking to get a list of the recent 4 posts and with it a link the the first (and only) category that the post is in.

$args = array(
        'numberposts' => '4',
        'offset' => '0'
    );

$recent_posts = wp_get_recent_posts($args);

foreach ($recent_posts as $recent) {
    echo '<li>'
     '<a href="' . get_permalink($recent["ID"]) . '" class="previous-post-thum">'
     get_the_post_thumbnail($recent["ID"], 'previous-posts-image')
     '</a>';

    echo '<p class="previous-cat-date">'
     get_the_time('F d,Y', $recent["ID"])
     '</p>';

    echo '<a class="previous-post-cat" href="'
     get_category_link($recent["ID"]) . '">'
     the_category($recent["ID"]) . '</a>';

    echo '<p class="previous-post-title"><a href="'
     get_permalink($recent["ID"]) . '" class="previous-title">'
     $recent["post_title"] . '</a></p>';

    $excerpt_text = apply_filters('the_excerpt', $recent['post_excerpt']);
    $number_of_characters = 350;

    echo '<div class="previous-post-excerpt">'
     substr($excerpt_text, 0, strrpos(substr($excerpt_text, 0, $number_of_characters), " "))
     '...' . '</div>';

    echo '<p class="previous-post-more">'
     '<a href="' . get_permalink($recent["ID"]) . '">Read More</a>'
     '</p>'
     '</li>';
}

This code works except for the category link.

1
  • 1
    Please file an edit and fix your Markup. Thanks.
    – kaiser
    Commented Mar 12, 2016 at 1:35

1 Answer 1

1
  • get_category_link() accept the category ID or object and you are passing the post ID.
  • the_category() accept Separator as a first parameter to separate multiple categories and again you are passing post ID.
  • You can use get_the_category to get all the categories and then display one of category information.

Example:-

$all_post_categories = get_the_category($recent["ID"]);
$category_obj = isset($all_post_categories[0]) && is_object($all_post_categories[0]) ? $all_post_categories[0] : false;
if ($category_obj) { ?>
    <a class="previous-post-cat" href="<?php echo get_category_link($category_obj); ?>"><?php
        echo $category_obj->name; ?>
    </a><?php
}

Your Answer

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

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