0

The Wordpress blog I'm building is published like a magazine; the first day of every month, several (nine, to be exact) posts are published in rapid succession. When a reader views one of these nine posts, the other 8 posts should appear in the sidebar.

I have a function I've written to accomplish this, but I'm having some issues that I'll describe below. Here's the code:

function getSidebarPosts($post_id){
    $ret = array();
    $parent = get_post($post_id, ARRAY_A);
    $sdate = strtotime($parent['post_date']);
    $month = date('m',$sdate);
    $year = date('Y',$sdate);

    $sargs = array(
        'monthnum'=>$month,
        'year'=>$year,
        'numberposts'=>9
    );
    $sposts = get_posts($sargs);
    foreach($sposts as $p){
        setup_postdata($p);
        $id = get_the_ID();
        if($id == $post_id){ continue; }
        $link = get_permalink($id);
        $title = get_the_title();
        $cats = wp_get_post_categories($id);
        $cat = get_category($cats[0]);
        $o = '<li><span>'.$cat->name.'</span> ';
        $o .= '<a href="'.$link.'">'.$title.'</a></li>';
        $ret[] = $o;
    }
    return $ret;
}

The parameter passed to this function is the ID of the post being displayed, so I need to retrieve all of the other posts published during the same month and year as the post being viewed. Wordpress doesn't generate any errors in any of this (nor does PHP, for that matter), but I simply get an empty result set and I'm unsure why that is. The code is fairly straightforward, but if I can clarify anything, do comment and let me know.

Oh, and I've tried adjusting the 'numberposts' parameter and that doesn't seem to have any effect. Also, each post has exactly one category.

Thank you!

1 Answer 1

0

I would take a look at the results of these before moving further:

$parent = get_post($post_id, ARRAY_A);
$sdate = strtotime($parent['post_date']);

Perhaps you can do something like this for testing:

function getSidebarPosts($post_id){
    $ret = array();
    $parent = get_post($post_id, ARRAY_A);
    $sdate = strtotime($parent['post_date']);
    $month = date('m',$sdate);
    $year = date('Y',$sdate);

    $ret[] = '<h3>Parent post:</h3>';
    $ret[] = print_r($parent, true);
    $ret[] = '<h3>Post date:</h3>';
    $ret[] = $parent['post_date'];
    $ret[] = '<h3>Post time:</h3>';
    $ret[] = $sdate;
    $ret[] = '<h3>Post converted date:</h3>';
    $ret[] = date('Y-m-d g:i:s a', $sdate);

    return $ret;
}

Please report back the output :)

1
  • Turns out that the post date was coming back as 2 months ago - changed it to post_modified and it worked like a charm :)
    – brettkelly
    Aug 22, 2010 at 2:39

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.