开发者

Get all posts from the same month and year for sidebar display

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('开发者_JAVA百科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!


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜