在侧边栏中显示与当前帖子属于同一类别的最近帖子

时间:2013-05-26 作者:Sasha

我使用的是一个修改后的版本,我试图在侧栏中显示与当前帖子(除了当前帖子)相同类别的最新帖子。

我是这样开始的,但有些事情不太好:

    $category = get_the_category($post->ID); 
    $current_cat = $category[0]->cat_name; //This will get me the first category assigned to the current post but since every post has only ONE cat. assigned to, it\'s good enough
   //Next, in my sidebar widget I have this:
    $my_query = new WP_Query(\'category_name=\'.$current_cat.\'&showposts=10\');
    while ($my_query->have_posts()) : $my_query->the_post();
    ...display my titles here ...
    unset($current_cat); //I\'m not sure I need to unset this variable?
    endwhile;
我不是一个真正的程序员,所以我正在努力理解逻辑,但我想学习。非常感谢您的任何建议/帮助!

谢谢你,亚历克斯

2 个回复
SO网友:Jeffrey Ponsen

试试这个

        // Get categories
        $categories = wp_get_post_terms( get_the_ID(), \'category\');

        // Check if there are any categories
        if( ! empty( $categories ) ) :

            // Get all posts within current category, but exclude current post
            $category_posts = new WP_Query( array(
                \'cat\'          => $categories[0]->term_id,
                \'post__not_in\' => array( get_the_ID() ),
            ) );

            // Check if there are any posts
            if( $category_posts->have_posts() ) :
                // Loop trough them
                while( $category_posts->have_posts() ) : $category_posts->the_post();
                    // Display posts
                    echo get_the_title() . \'<br />\';
                endwhile;
            endif;
        endif;
此外,请查看此页面以了解有关WP_Query 用于在帖子中循环,并且不要忘记使用wp_reset_postdata();

SO网友:Devoted

Try this way:

global $post;
$category = get_the_category($post->ID); 
$current_cat = $category[0]->cat_name; //This will get me the first category assigned to the current post but since every post has only ONE cat. assigned to, it\'s good enough

$my_query = new WP_Query(\'category_name=\'.$current_cat.\'&showposts=10\');
while ($my_query->have_posts()) : $my_query->the_post();
    the_title();
unset($current_cat); //I\'m not sure I need to unset this variable?
endwhile;
结束

相关推荐

Categories sorting

我正在使用下面的代码来弹出自定义帖子类型及其类别,所以类别1---岗位1---岗位2第二类——岗位1——岗位2——岗位3等。这对我来说很好,但是我希望能够按count对我的类别进行排序,所以orderby=count,这样,在我下面的代码中不起作用的时候,具有大量帖子的类别将排在列表的顶部,知道为什么吗?非常感谢您的帮助 <?php // List posts by the terms for a custom taxonomy of any post type