I'm working on a shortcode function that returns a category image, a link to the category, the last three posts in that category, and another link to the category. See my code below:

    function bm_caticons_listing($atts) {
        extract( shortcode_atts( array(
            'include' => '',
            'exclude' => '',
            'small' => 'true'
        ), $atts ) );
        if ($atts['include']) $include = "&include=".$atts['include'];
        if ($atts['exclude']) $exclude = "&exclude=".$atts['exclude'];
        if ($atts['small'] == 'false') $small = "&small=false";
        $listing_code .= '<table class="cat-nav">';
        foreach(get_categories("orderby=name&order=ASC&hide_empty=0".$include.$exclude) as $category) {
            if (category_description($category->cat_ID)) { $desc = category_description($category->cat_ID); } else { $desc = "Coming soon!";}
            if ($category->count > 0) {
                $seemore = '<br /><a href="'.get_category_link( $category->term_id ).'">See more.</a>';} 
                else {$seemore = '';}
           $listing_code .= '<tr><td>'.get_cat_icon("echo=false".$small."&class=caticon&cat=".$category->cat_ID).'</td><td valign="top" style="padding: 5px;"><a href="'.get_category_link( $category->term_id ).'"><h2 style="font-size: 130%;">'.$category->cat_name.'</h2></a>'.category_description($category->cat_ID).'<br />';
//$listing_code .= "I think I need a loop here.";
$listing_code .= $seemore.'</td></tr>';
        $listing_code .= '</table>';
        return $listing_code;

My issue is, with the way the WP loop examples are written, I can't figure out a good way to output the three latest posts as links in a manner that can be stored as a variable (to be returned as the shortcode output). Any help would be appreciated. Thanks!

  • do you need the table or is this just "in the meanwhile until..." – kaiser Feb 14 '11 at 17:35

First, need to lose query_posts() - it should never be used for secondary loops.

Try something like this:

$posts = get_posts( array(
    'cat' => $category->term_id,
    'numberposts' => 3,

foreach( $posts as $post ) {

    $listing_code .= get_permalink( $post->ID ); //or whatever
  • Thanks, that's great! One note though -- get_posts(); doesn't take a variable called "posts_per_page"; instead, it's numberposts. I've edited your answer to reflect this, though please let me know if this is incorrect! – aendrew Feb 14 '11 at 19:31
  • @aendrew ah, yep - I forgot about it (again). :) Actually it is supposed to take either, but there is some lingering bug that prevents that. – Rarst Feb 14 '11 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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